Data structures – Lists
A list is a sequence of variable length. Lists can be modified and items can be added and removed from the list.
A list is defined as a sequence of objects separated as commas and enclosed in []
An empty list can be defined with []
Examples
mylist = [1,2,3,4,5]
Operations on lists
+ concatenates the elements of two lists
* repeats the elements of a list
[] is also used to select items from a list
Examples
[1,2] + [3,4] results in [1,2,3,4]
2 * [1,2] results in [1,2,1,2]
t = [1,2,3,4]
t [1] is 2
t [1: 3] is [2,3,4]
t [2:] is [2,3,4]
t [: 3] is [1,2,3]
Operations on tuples also apply to lists.
The range (i, f, step) operation creates a list of numbers from start to end from step to step.
If i is omitted it is worth 0, if step is omitted it is worth 1
Example
range (2) is [1,2]
range (5.7) is [5,6,7]
range (8,12,2) is [8,10,12]
List methods
append (e) – add an element to the end of the list
extend (l) – add a list at the end
insert (i, n) – insert an element at position n-1
pop (n) – extract and return element n from the list
remove (n) – remove item n from the list
reverse () – invert the list items
count (e) – returns the number of times e appears in the list
index (e) – returns the position of the first occurrence of e in a list