List Iteration and Comprehensions

More 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

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

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.