15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

6.11. Lists<br />

Like strings, lists provide sequential storage through an index offset and access to single or consecutive<br />

elements through slices. However, the comparisons usually end there. Strings consist only of characters<br />

and are immutable (cannot change individual elements), while lists are flexible container objects that<br />

hold an arbitrary number of <strong>Python</strong> objects. Creating lists is simple; adding to lists is easy, too, as we<br />

see in the following examples.<br />

The objects that you can place in a list can include standard types and objects as well as user-defined<br />

ones. Lists can contain different types of objects and are more flexible than an array of C structs or<br />

<strong>Python</strong> arrays (available through the external array module) because arrays are restricted to containing<br />

objects of a single type. Lists can be populated, empty, sorted, and reversed. Lists can be grown and<br />

shrunk. They can be taken apart and put together with other lists. Individual or multiple items can be<br />

inserted, updated, or removed at will.<br />

Tuples share many of the same characteristics of lists and although we have a separate section on<br />

tuples, many of the examples and list functions are applicable to tuples as well. The key difference is<br />

that tuples are immutable, i.e., read-only, so any operators or functions that allow updating lists, such<br />

as using the slice operator on the left-hand side of an assignment, will not be valid for tuples.<br />

How to Create and Assign Lists<br />

Creating lists is as simple as assigning a value to a variable. You handcraft a list (empty or with<br />

elements) and perform the assignment. Lists are delimited by surrounding square brackets ( [ ] ). You<br />

can also use the factory function.<br />

>>> aList = [123, 'abc', 4.56, ['inner', 'list'], 7-9j]<br />

>>> anotherList = [None, 'something to see here']<br />

>>> print aList<br />

[123, 'abc', 4.56, ['inner', 'list'], (7-9j)]<br />

>>> print anotherList<br />

[None, 'something to see here']<br />

>>> aListThatStartedEmpty = []<br />

>>> print aListThatStartedEmpty<br />

[]<br />

>>> list('foo')<br />

['f', 'o', 'o']<br />

How to Access Values in Lists<br />

Slicing works similar to strings; use the square bracket slice operator ([ ] ) along with the index or<br />

indices.<br />

>>> aList[0]<br />

123<br />

>>> aList[1:4]<br />

['abc', 4.56, ['inner', 'list']]<br />

>>> aList[:3]<br />

[123, 'abc', 4.56]<br />

>>> aList[3][1]<br />

'list'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!