- publishing free software manuals
An Introduction to Python
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
ISBN 0954161769
RRP £12.95 ($19.95)

Sales of this book support the Python Software Foundation! Get a printed copy>>>

3.1.4 Lists

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.

    >>> a = ['spam', 'eggs', 100, 1234]
    >>> a
    ['spam', 'eggs', 100, 1234]

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:

    >>> a[0]
    'spam'
    >>> a[3]
    1234
    >>> a[-2]
    100
    >>> a[1:-1]
    ['eggs', 100]
    >>> a[:2] + ['bacon', 2*2]
    ['spam', 'eggs', 'bacon', 4]
    >>> 3*a[:3] + ['Boo!']
    ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam',
     'eggs', 100, 'Boo!']

Unlike strings, which are immutable, it is possible to change individual elements of a list:

    >>> a
    ['spam', 'eggs', 100, 1234]
    >>> a[2] = a[2] + 23
    >>> a
    ['spam', 'eggs', 123, 1234]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

    >>> # Replace some items:
    ... a[0:2] = [1, 12]
    >>> a
    [1, 12, 123, 1234]
    >>> # Remove some:
    ... a[0:2] = []
    >>> a
    [123, 1234]
    >>> # Insert some:
    ... a[1:1] = ['foo', 'xyzzy']
    >>> a
    [123, 'foo', 'xyzzy', 1234]
    >>> # Insert (a copy of) itself at the beginning
    >>> a[:0] = a
    >>> a
    [123, 'foo', 'xyzzy', 1234, 123, 'foo', 'xyzzy', 1234]
    >>> # Clear the list: replace all items with an empty list
    >>> a[:] = []
    >>> a
    []

The built-in function len() also applies to lists:

    >>> len(a)
    8

It is possible to nest lists (create lists containing other lists), for example:

    >>> q = [2, 3]
    >>> p = [1, q, 4]
    >>> len(p)
    3
    >>> p[1]
    [2, 3]
    >>> p[1][0]
    2
    >>> p[1].append('xtra')     # See section 5.1
    >>> p
    [1, [2, 3, 'xtra'], 4]
    >>> q
    [2, 3, 'xtra']

Note that in the last example, p[1] and q really refer to the same object! We'll come back to object semantics later.

ISBN 0954161769An Introduction to PythonSee the print edition