Sequence Types - List¶
Indices and tables¶
List¶
MUTABILITY: Mutable
A list is an ordered sequence (i.e. a collection) of zero or more arbitrary Python objects (i.e. object references. The items need not all be the same type and you can nest other collection types if desired.
Since lists are mutable, you can modify individual elements after creation without forcing Python to create a new object.
Tip
Many people subscribe to the following idiom:
- Use tuples for heterogeneous data sets (like structs) that you deal with as a coherent unit.
- Use lists for homogeneous data sets where you deal with each item in the list individually.
Although, nothing in Python requires, or strictly enforces, this.
An example of this is having a list of pixels, where each pixel is a 3-tuple of RGB color values.
Lists can be constructed in a variety of ways:
Using square brackets
[]
. For example:To create a list with 0 items:
>>> foo = [] >>> foo []
To create a list with 1 item, unlike a tuple, a trailing comma is not required:
>>> foo = [1] >>> foo [1]
To create a list of 2 or more items:
>>> foo = [1, 2, 3] >>> foo [1, 2, 3]
Note
Unlike with a tuple where the parenthesis can be omitted in some situations, a list always requires the use of the brackets or the list constructor.
Using an expression in square brackets
[]
to create a list comprehension. For example:>>> foo = [x.upper() for x in ('foo', 'bar', 'baz')] ['FOO', 'BAR', 'BAZ']
Using the
list
constructor, which allows you to do several things:With no arguments, it creates an empty list:
>>> foo = list() >>> foo []
When passed something it can iterate over, it builds a list from each of the items (this is a form of type conversion):
>>> foo = list('a1b2c3') >>> foo ['a', '1', 'b', '2', 'c', '3']
>>> bar = (1, 2, 3) >>> bar (1, 2, 3) >>> type(bar) tuple >>> baz = list(bar) >>> baz [1, 2, 3] >>> type(baz) list
When passed a list, this is one way of shallow-copy ing the list:
>>> foo = [1, 2, 3] >>> bar = list(foo) >>> bar [1, 2, 3]
List Specific Methods¶
There is only one list specific method.
-
sort
(*, key=None, reverse=None)¶ This method sorts the list in place, using only
<
comparisons between items. Thekey
argument can be used to pass in a function that operates on each item to extract a comparison key just prior to the comparison being performed. The sort can be reversed by settingreverse
toTrue
.>>> foo = ['foo', 'bar', 'baz'] >>> foo.sort() >>> foo ['bar', 'baz', 'foo']
Warning
If any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
Try it!
Try creating the following objects:
- An empty list.
- A list of 1 item.
- A list of 2 items.
- A list from the string “abc”.
- A list, from a list. Prove the lists are different objects.
- A list of a string and another list.
- A list of 2 lists.
- A sorted list from the string, “j48af”