3.4.1. Lists

Lists are sequences of things. What kinds of things? Well, anything that can be a thing in Python. That is one key fact about lists. A list can be a higgledypiggledy assortment. One list can contain a number, a string, and another list. You should certainly use lists when you want to remember the order in which you saw a sequence of things. But there are other reasons to use lists. They are in some ways the default container type.

Python uses square brackets to enclose lists and commas to separate the elements, so X, Y, and Z are all valid lists:

>>> X = [24, 3.14, 'w', [1,'a']] #  List with 4 items
>>> Y = [100]    # list with one item
>>> Z = [] #empty list

Note in particular that one of the elements of X is itself a list. More on lists containing lists below. The name list is special in Python, because it refers to the type list:

>>> list
<type 'list'> Creating lists

You can use the type name as function of to create lists. So consider the following:

>>> L = list('hi!')

Python interprets this as a request to make a list that contains the same things as the string hi!; that string contains 3 characters, so Python makes L be a list containing three characters:

>>> L
['h', 'i', '!']

Use of the the type as a function that creates instances of the type is a standard practice in Python, so the list function can be fed any sequence as an argument, and it returns a list containing the same elements. A special case is calling list with no arguments at all:

>>> M = list()

This returns a special list called the empty list, which is of length 0, and contains no elements at all:

>>> M

This may seem useless, but it is a great convenience when programming the result be something that is well defined and legal when all the elements have been removed from a list. Indexing lists, list slices

A list is an index where the indices are numbers; items are referred to by their integer indices:

>>> X[0]   # 1st element
>>> X[1]   # 2nd element
>>> X[-1]   # last element

Thus, indexing starts with 0. This means the highest index that retrieves anything is 1 less than the length of the list. List X has length 4, so the following raises an IndexError:

>>> X[4]   # Raises exception!
IndexError: list index out of range

Python also provides easy access to subsequences of a list. The following examples illustrate how to make such references:

>>> X[0:2] # list of 1st and 2nd elements
[24, 3.14]
>>> X[:-1] # list excluding last element

References to subsequences of a list are called slices.

List can be concatenated a longer lists:

>>> X + Y # Concatenation!
[24, 3.14, 'w', [1,'a'], 100]

Lists allow value assignments, which change the value of a reference in place (in place assignment):

>>> X[2] = 5
>>> X
[24, 3.14, 5, [1,'a']]
>>> X[0:2]
[24, 3.14]
>>> X[0:2] = [1,3]
>>> X
[1, 3, 5, [1,'a']]

Only list-values can be assigned to slices:

>>> X[0:2] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable

The Error message here “TypeError: can only assign an iterable” refers to a general class containing containers called iterables, the root of the the tree in the Section on More_Python types. We’ll talk more about iterables later. The important point for now is that iterables include all container including lists but not integers, so:

>>> X[0:2] = [1]

works, but

>>> X[0:2] = 1

does not. A list slice must be filled in by a list; any iterable can be easily turned into a list, but 1 cannot.

Learning how to read and interpret Python errors is an important part of being able to write simple programs in Python. Properly understood, Python’s error-reporting will make it easier for you to fix errors.

Finally, there are two simple ways of adding elements to the end of a list You can use append and extend. The append method add 1 element to end of a list:

>>> X
[24, 3.14, 5, [1,'a']]
>>> X.append([2,'b'])
>>> X
[24, 3.14, 5, [1,'a'],[2,'b']]

The extend method takes a list as its argument and adds all the elements of that list:

>>> X
[24, 3.14, 5, [1,'a'],[2,'b']]
>>> X.extend([2,'b'])
>>> X
[24, 3.14, 5, [1,'a'],[2,'b'],2,'b']

Be sure to understand the difference between append and extend. Both are quite useful.

Another important operation on lists is checking their contents. So:

>>> 24 in X
>>> 6 in X

In fact, the in operator works for all Python containers.


in is called an operator because it can occur in between its arguments. Lists containing lists

We introduced the list structure by saying a list could contain anything. That includes a list. Lists of lists are useful for many purposes. One of the most intuitive is to represent a table. Suppose we want to represent the following table from some dataset in Python.

 42 & 3.14 & 7 \\
 2 & 4 & 0 \\
 14 & 0 & 0

We can do that as follows:

>>> Table = [[42, 3.14,7],[2,4,0],[14,0,0]]
>>> Table[0]
[42, 3.14,7]

This means to retrieve the value 42, we can do:

>>> FirstRow = Table[0]
>>> FirstRow[0]

But Python allows any expression which has a list as its value to be followed by [index]. That includes the expression Table[0]. It is much more convenient and Pythonic to do this in one step:

>>> Table[0][0]

So in general, thinking of a table as a list of rows, each of which is a list, we can access the element in row i, column j, with Table[i][j]. List operators and methods

In all the following examples, L is a list.


Returns length of L.

x in L

Returns True if x is in L. Otherwise returns False.

L.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).


Equivalent to a.insert(len(a), x).


Return the index in the list of the first item whose value is x. It is an error if there is no such item.


Remove the first item from the list whose value is x. It is an error if there is no such item.


Sort the items of the list. Much more to be said about this. But it changes the list.


Reverse the elements of the list, in place.


Return the number of times x appears in the list.

See also

For a nice overview of list operations, see the Google’s tutorial. This is geared toward the more advanced student. For a real programmer’s discussion of Python lists, addressing questions like what’s faster, assignment or insertion, or what’s faster, insertion at the beginning, or insertion at the end, see Fredrik Lundh’s effbot.org discussion.