Online Book Reader

Home Category

Learning Python - Mark Lutz [127]

By Root 1874 0
generally, lists respond to all the sequence operations we used on strings in the prior chapter, including iteration tools:

>>> 3 in [1, 2, 3] # Membership

True

>>> for x in [1, 2, 3]:

... print(x, end=' ') # Iteration

...

1 2 3

We will talk more formally about for iteration and the range built-ins in Chapter 13, because they are related to statement syntax. In short, for loops step through items in any sequence from left to right, executing one or more statements for each item.

The last items in Table 8-1, list comprehensions and map calls, are covered in more detail in Chapter 14 and expanded on in Chapter 20. Their basic operation is straightforward, though—as introduced in Chapter 4, list comprehensions are a way to build a new list by applying an expression to each item in a sequence, and are close relatives to for loops:

>>> res = [c * 4 for c in 'SPAM'] # List comprehensions

>>> res

['SSSS', 'PPPP', 'AAAA', 'MMMM']

This expression is functionally equivalent to a for loop that builds up a list of results manually, but as we’ll learn in later chapters, list comprehensions are simpler to code and faster to run today:

>>> res = []

>>> for c in 'SPAM': # List comprehension equivalent

... res.append(c * 4)

...

>>> res

['SSSS', 'PPPP', 'AAAA', 'MMMM']

As also introduced in Chapter 4, the map built-in function does similar work, but applies a function to items in a sequence and collects all the results in a new list:

>>> list(map(abs, [−1, −2, 0, 1, 2])) # map function across sequence

[1, 2, 0, 1, 2]

Because we’re not quite ready for the full iteration story, we’ll postpone further details for now, but watch for a similar comprehension expression for dictionaries later in this chapter.

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for strings. However, the result of indexing a list is whatever type of object lives at the offset you specify, while slicing a list always returns a new list:

>>> L = ['spam', 'Spam', 'SPAM!']

>>> L[2] # Offsets start at zero

'SPAM!'

>>> L[−2] # Negative: count from the right

'Spam'

>>> L[1:] # Slicing fetches sections

['Spam', 'SPAM!']

One note here: because you can nest lists and other object types within lists, you will sometimes need to string together index operations to go deeper into a data structure. For example, one of the simplest ways to represent matrixes (multidimensional arrays) in Python is as lists with nested sublists. Here’s a basic 3 × 3 two-dimensional list-based array:

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

With one index, you get an entire row (really, a nested sublist), and with two, you get an item within the row:

>>> matrix[1]

[4, 5, 6]

>>> matrix[1][1]

5

>>> matrix[2][0]

7

>>> matrix = [[1, 2, 3],

... [4, 5, 6],

... [7, 8, 9]]

>>> matrix[1][1]

5

Notice in the preceding interaction that lists can naturally span multiple lines if you want them to because they are contained by a pair of brackets (more on syntax in the next part of the book). Later in this chapter, you’ll also see a dictionary-based matrix representation. For high-powered numeric work, the NumPy extension mentioned in Chapter 5 provides other ways to handle matrixes.

Changing Lists In-Place

Because lists are mutable, they support operations that change a list object in-place. That is, the operations in this section all modify the list object directly, without requiring that you make a new copy, as you had to for strings. Because Python deals only in object references, this distinction between changing an object in-place and creating a new object matters—as discussed in Chapter 6, if you change an object in-place, you might impact more than one reference to it at the same time.

Index and slice assignments

When using a list, you can change its contents by assigning to either a particular item (offset) or an entire section (slice):

>>> L = ['spam', 'Spam', 'SPAM!']

>>> L[1] = 'eggs' # Index assignment

>>> L

['spam', 'eggs', 'SPAM!']

>>>

Return Main Page Previous Page Next Page

®Online Book Reader