Next: First Steps Towards Up: Using Python as Previous: Strings

Lists

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.


>>> a = ['foo', 'bar', 100, 1234]
>>> a
['foo', 'bar', 100, 1234]
>>>
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:


>>> a[0]
'foo'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['bar', 100]
>>> a[:2] + ['bletch', 2*2]
['foo', 'bar', 'bletch', 4]
>>> 3*a[:3] + ['Boe!']
['foo', 'bar', 100, 'foo', 'bar', 100, 'foo', 'bar', 100, 'Boe!']
>>>
Unlike strings, which are immutable, it is possible to change individual elements of a list:


>>> a
['foo', 'bar', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['foo', 'bar', 123, 1234]
>>>
Assignment to slices is also possible, and this can even change the size of the list:


>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a     # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>>
The built-in function len() also applies to lists:


>>> len(a)
8
>>>
It is possible to nest lists (create lists containing other lists), for example:


>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra')     # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
>>>
Note that in the last example, p[1] and q really refer to the same object! We'll come back to object semantics later.


guido@cwi.nl