Main Page | Recent changes | Edit this page | Page history

Printable version | Disclaimers | Privacy policy

Not logged in
Log in | Help
 

Reference: Lists

From 6.00 reference wiki

Strings | Lists | Dictionaries

A list in Python is an ordered group of items. It is a very general structure. You can have any kind of things in a lists, and they don't have to be all of the same type. For instance, you could put integers, floats and strings all on the same list:

 >>> x = ["MIT", 1, "Harvard", 0, "Yale", -1.5]

Lists are sequences, and can be indexed and sliced like strings.

Lists can also contain lists:

 >>> x = [ ["MIT", 1, 1000, 'a'], ["Harvard", 0, 100, 'b'], ["Yale", -1.5, -900, 'c'] ]
 >>> len(x)
 3
 >>> len(x[0])
 4

Contents

Basics

Iterating over

Using a for loop, we can iterate over the elements of a list in order.

>>> for x in ['first', 'second', 'third', 'fourth', 'fifth']:
        print x
first
second
third
fourth
fifth

In fact, you should be familiar with the following type of loop:

for x in range(10):
    print x

The range function actually returns a list

 >>> range(10)
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

So you've been iterating over lists all along.

Length of a List

len allows you to count the number of elements in a list:

>>> len([1, 2, 3])
3
>>> len([])
0

Equality

Lists can be compared for equality. Two lists are equal if and only if they are of the same length and they have elements that are equal and in the exact same order.

>>> [1, 2, 3] == [0, 1, 2]
False
>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] == [1, '2', 3]   # the string '2' is not == the int 2
False


Indexing, Slicing and Deleting

Like strings, lists can be indexed and sliced.

>>> list = ["MIT", 1, "Harvard", 0, "Yale", -1.5]
>>> list[2]
'Harvard'
>>> list[3:]
[0, 'Yale', -1.5]
>>> list[-2:]
['Yale', -1.5]

See the string reference if you're unclear about the basic notions of indexing and slicing.

Indexed assignment

Since lists are mutable, lists differ (importantly) from strings in that we can assign new values to the items in a list:

>>> list = ["MIT", 1, "Harvard", 0, "Yale", -1.5]
>>> list[0] = "Massachusetts Institute of Technology"
>>> list
['Massachusetts Institute of Technology', 1, 'Harvard', 0, 'Yale', -1.5]

The second assignment statement above is a little special: it does not affect what object the name list refers to; it mutates the list by changing the value at index 0 in the list.

As with reading from indices, we get index-out-of-bounds errors if we try to assign a value to an index that is too large (index >= len(list)). The list does not grow automatically (although we can use append as discussed later).

Slice assignment

We can mutate a list by assigning a new (list) value to a slice of that list:

>>> list = ["MIT", 1, "Harvard", 0, "Yale", -1.5]
>>> list[2:4] = ["Williams", 1]
>>> list
['MIT', 1, 'Williams', 1, 'Yale', -1.5]

In such assignments, the new values don’t even have to be the same length as the slice. Longer values will result in adding elements to the list; shorter values will result in elements being removed:

>>> list = ["MIT", 1, "Harvard", 0, "Yale", -1.5]
>>> list[-1:] = [1, 2, 3, 4]
>>> list
['MIT', 1, 'Harvard', 0, 'Yale', 1, 2, 3, 4]
>>> list[:] = ["only one now"]
>>> list
['only one now']

It’s even possible to prepend things onto the start of a list by assigning to an empty slice:

>>> list = ["MIT", 1, "Harvard", 0, "Yale", -1.5]
>>> list[:0]
[]
>>> list[:0] = ["something appended", "at the start"]
>>> list
['something appended', 'at the start', 'MIT', 1, 'Harvard', 0, 'Yale', -1.5]

Deleting elements

Elements can be removed from a list by using the del operator.

>>> list = ["MIT", 1, "Harvard", 0, "Yale", -1.5]
>>> list
['MIT', 1, 'Harvard', 0, 'Yale', -1.5]
>>> del list[0]
>>> list
[1, 'Harvard', 0, 'Yale', -1.5]

Mutability and Aliasing

Unlike strings, lists are mutable. This can result in aliasing effects (and hard to track down bugs):

 >>> x = [1, 2, 3]
 >>> y = x
 >>> x[1] = 5
 >>> x
 [1, 5, 3]
 >>> y
 [1, 5, 3]

The problem is that the assignment statement (y = x) doesn't create a copy of the list itself: it just copies the reference. You can use the following approach to create a copy, and avoid aliasing:

 >>> x = [1, 2, 3]
 >>> y = x[:]       # slices are always copies
 >>> x[1] = 5
 >>> x
 [1, 5, 3]
 >>> y
 [1, 2, 3]

Combining Lists: Addition and Multiplication

Addition

+ operator

You can add two lists together to produce a new list which contains the sequence from the first list followed by the sequence from the second list.

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> [1, 2, 3] + [] 
[1, 2, 3]

In fact, you can concatenate an aribtrary number of lists together:

Mutability note:
The + operator always creates a new list.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> z = x + y       # create a new list from x and y
>>> z
[1, 2, 3, 4, 5, 6]
>>> z[0] = 99       # modify new list
>>> z
[99, 2, 3, 4, 5, 6]
>>> x               # old list is unmodified
[1, 2, 3] 

append method

You can add a list to the end of an existing list, using the append list method.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x.append(y)    # mutate/modify the list referred to by x
>>> x
[1, 2, 3, 4, 5, 6]
>>> y              # y is unmodified
[4, 5, 6]

Mutability note:
The append method modifies the list it acts on (the variable to the left of the period; see above).

Multiplication

'Multiplying' a list by an integer value n returns a new list which contains the original sequence of elements repeated n times.

 >>> x = [1, 2, 3]
 >>> z = x * 3
 >>> z
 [1, 2, 3, 1, 2, 3, 1, 2, 3]
 >>> x                       # original list unmodified
 [1, 2, 3]

Multiplication and Mutability

Multiplication can be a useful way to initialize lists:

>>> zeros = [0] * 5
>>> print zeros
[0, 0, 0, 0, 0]

This works for any data type:

>>> foos = ['foo'] * 8
>>> print foos
['foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo']

with a caveat related to mutability. When building a new list by multiplying, Python copies each item by reference. This poses a problem for mutable items, for instance suppose we wanted to represent a 4-by-5 matrix of numbers as a list of lists. Here each element is itself a list. You might guess that the easy way to generate a two dimensional matrix would be:

matrix = [ [0] * 4 ] * 5

and this works, but probably doesn't do what you expect:

>>> matrix=[ [0] * 4 ] * 5
>>> print matrix        # the output of this looks good...
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> matrix[0][2]=1      # but lets try to update one element of the matrix
>>> print matrix        # the output isn't what we'd expect...
[[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]

What's happening here is that Python is using the same reference to the inner list as the elements of the outer list. Another way of looking at this issue is to examine how Python sees the above definition:

>>> innerlist = [0] * 4
>>> matrix = [innerlist] * 5
>>> print matrix
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> matrix[2] = 1
>>> print matrix
[[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]

Other operations

Sorting lists

Sorting lists is easy with a sort method.

>>> list = [2, 3, 1, 'a', 'b']
>>> list.sort()
>>> list
[1, 2, 3, 'a', 'b']

Note that the list is sorted in place (ie. the list is mutated), and the sort method returns None.

There are some optional parameters:

 sort(cmp, key, reverse)
cmp
The function to be used for sorting. The function has the following specification:
cmp(x, y) returns 0 if x and y are equal.
cmp(x, y) returns -1 if x is less than y.
cmp(x, y) returns 1 if x is greater than y.
key
Function to be executed with each element. The list is sorted by the return-values of the function.
(experiment with this if you're interested)
reverse
Sort ascending: True or False. Defaults to False.

(these notes have been adapted/expanded from the programming:python wikibook)

Retrieved from "http://slice.csail.mit.edu../../../l/i/s/Reference%7E_Lists_4803.html"

This page has been accessed 122 times. This page was last modified 01:32, 24 February 2006 by 6.00 reference wiki user Asfandyar.


[Main Page]
Main Page
Recent changes

Edit this page
Discuss this page
Page history
What links here
Related changes

Special pages
Bug reports