
22
|
Python Pocket Reference
Lists
Lists are mutable (changeable) arrays of object references,
accessed by offset.
Literals and creation
Lists are written as comma-separated series of values
enclosed in square brackets.
[]
An empty list.
[0, 1, 2, 3]
A four-item list: indexes 0...3.
alist = ['spam', [42, 3.1415], 1.23, {}]
Nested sublists: alist[1][0] fetches 42.
alist = list('spam')
Creates a list by calling the type constructor with a
sequence.
alist = [x**2 for x in range(9)]
Creates a list by collecting expression results (list com-
prehension).
Operations
Operations include all sequence operations (see Table 3, ear-
lier in this book), plus all mutable sequence operations (see
Table 4, earlier in this book), plus the following list methods.
alist.append(x)
Inserts the single object x at the end of alist, changing
the list in-place.
alist.extend(x)
Inserts each item in any sequence x at the end of alist in-
place (an in-place
+). Similar to alist[len(alist):] =
list(x)
.