Next / Previous / Contents / TCC Help System / NM Tech homepage

7.3. The list type

Python's list type represents a sequence of objects of any type. Lists support all the operations described above under intrinsics for sequences, in addition to the operations described below.

7.3.1. Constructing a list

To create a list, place zero or more objects between a pair of square brackets, separated by commas. Examples:

[]                     # An empty list.
["baked beans"]        # List containing one item.
[23, 30.9, "x"]        # List containing three items.

7.3.2. List comprehensions

In versions 2.2 and beyond, you can also use a list comprehension to create a list. The general form is:

[ e for v1 in s1
      for v2 in s2 ...
        ...
          if c ]

where e is some expression, followed by zero or more for clauses, optionally followed by an if clause. The equivalent in pre-2.2 Python would be:

temp = []
for v1 in s1:
    for v2 in s2 ...:
        ...
        if c:
            temp.append ( e )

The value of the expression is the final value of temp.

A few examples of list comprehensions, taken from actual evaluations in Python calculator mode:

>>> [(n,a) for n in range(3) for a in ('a', 'b')]
[(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
>>> [(i,j) for i in range(1,4) for j in range(1,4) if i != j]
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
>>> [10*x+y for x in range(1,4) for y in range(x)]
[10, 20, 21, 30, 31, 32]

7.3.3. Slice assigment

Because lists are mutable, lists with slice operators can appear as destinations in an assign statement. The expression being assigned must be a sequence, and the elements of that slice of the list are replaced by the elements of that sequence. For example:

>>> L=[0,1,2,3,4,5,6,7,8]
>>> L[4:6]
[4, 5]
>>> L[4:6] = [17, 18, 19, 20]
>>> L
[0, 1, 2, 3, 17, 18, 19, 20, 6, 7, 8]
>>> 

7.3.4. List functions

list(i)

Creates a list, a sequence of values that is mutable (its contained values can be changed, added, or deleted). The value i is a sequence of values or any object that can be iterated over.

range([start,]limit[,step])

Creates a list containing a sequence of integers. There are three forms:

  • range(limit) creates the list [0, 1, .., limit-1]. Note that the list stops just before element limit. For example, range(3) returns the list [0, 1, 2].

  • range(start,limit) creates the list [start, start+1, ..., limit-1].

  • range(start,limit,step) returns the list [start,start+step,start+2*step,...], stopping just before the element that would equal or exceed limit in the direction of the step.

    For example, range(4,10,2) returns [4, 6, 8], and range(3,-1,-1) returns [3, 2, 1, 0].

xrange([start,]limit[,step])

Effectively produces the same values as the range() function, but doesn't take up all the space, which is nice for iterating over huge sequences.

7.3.5. List methods

All list objects have these methods, where L is any list:

L.append(x)

Append a new element x to the end of list L. Does not return a value.

L.pop([i])

Remove and return element i from L. The default value for i is -1, so if you pass no argument, the last element is removed.

L.count(x)

Return the number of elements of L that compare equal to x.

L.index(x)

If L contains any elements that equal x, return the index of the first such element, otherwise raise a ValueError exception.

L.insert(i,x)

Insert a new element x into list L just before the ith element, shifting all higher-number elements to the right. No value is returned. Example: if L is [0,1,2], then L.insert(1,99) changes L to [0,99,1,2].

L.remove(x)

Remove the first element of L that is equal to x. If there aren't any such elements, raises ValueError.

L.reverse()

Reverses the elements of L in place; does not return a result.

L.sort()

Sort list L in place using the default rules for comparing objects. Does not return a result.

L.sort(f)

Sort list L in place using function f to compare pairs of objects to see in which order they should go. The calling sequence and result of this function should be the same as for the cmp() function.

For example, here is a function that can be used to sort numbers and strings in descending order, demonstrated in calculator mode:

>>> def descendingCmp(a,b):
...     return  - cmp(a,b)
... 
>>> L=[0,39,18,99,40]
>>> L.sort()
>>> L
[0, 18, 39, 40, 99]
>>> L.sort(descendingCmp)
>>> L
[99, 40, 39, 18, 0]
>>>