A list
is created by surrounding them with
[]
's and separating the values with commas
(,
). A list
can be created, expanded
and reduced. An empty list
is simply
[]
. As with tuple
s, an extra comma
at the end of the list
is graciously
ignored.
Examples:
myList = [ 2, 3, 4, 9, 10, 11, 12 ]
history = [ ]
The elements of a list
do not have to be
the same type. A list
can be a mixture of any
Python data types, including list
s,
tuple
s, string
s and
numeric types.
A list
permits a sophisticated kind of
display called a comprehension. We'll revisit
this in some depth in the section called “List Comprehensions”. As a
teaser, consider the following:
>>>
print [ 2*i+1 for i in range(6) ]
[1, 3, 5, 7, 9, 11]
This statement creates a list
using a list
comprehension. A comprehension starts with a candidate
list
(range
(
6
), in this example) and derives the
list
values from the candidate
list
(using 2*i+1
in this example).
A great deal of power is available in comprehensions, but we'll save the
details for a later section.