Lists
Construction and indexing of lists is similar to tuples:
>>> x = [1, 2, 3, 4, 5]
>>> x
[1, 2, 3, 4, 5]
>>> x[0] # first element
1
>>> x[3] # fourth element
4
>>> x[-1] # last element
5
>>> x[1:] # all but the first element
[2, 3, 4, 5]
Lists are mutable, meaning that we can change them in place. Here is how:
>>> x = [1, 2, 3, 4, 5]
>>> x
[1, 2, 3, 4, 5]
>>> x.append(7)
>>> x
[1, 2, 3, 4, 5, 7]
>>> x.insert(2, 6) # insert 6 at index 2
>>> x
[1, 2, 6, 3, 4, 5, 7]
>>> x.extend([8,9]) # extend by another list
>>> x
[1, 2, 6, 3, 4, 5, 7, 8, 9]
Operations like .insert, .extend, .append, and so on, are not expressions. They do now have any return value, but have side-effects that modify the list in place. Operations like these cause too much pain in programs, causing errors usually very hard to detect. We are not fond of side-effects, we like expressions that return values. Here are the expression equivalents of the above operations:
>>> x = [1, 2, 3, 4, 5]
>>> x
[1, 2, 3, 4, 5]
>>> x + [7] # concatenation
[1, 2, 3, 4, 5, 7]
>>> x[:2] + [6] + x[2:] # insert 6 at index 2
[1, 2, 6, 3, 4, 5]
>>> x + [8,9] # extend by another list
[1, 2, 3, 4, 5, 8, 9]
>>> x
[1, 2, 3, 4, 5]
As you see, the list x remains unchanged after these operations. To actually change x, you need to assign the result back to x; unless you do that the original list remains unchanged. Do this assignment by an explicit addition construction, do not ever use += operator, which has a different semantics than the standard one when used with mutable data types like lists.
Finally, here are some useful functions on lists:
>>> x = [1, 2, 3]
>>> len(x) # length of the list
3
>>> 2 in x # membership test
True