Iterations and Comprehensions

NoteIs there any other Python iterator besides while and for loops?

As we know from the previous section, while and for loops can handle most repetitive tasks programs need to perform. However, Python provides additional tools to make loops easier to write/read and more efficient. One of the most prominent tools is list comprehension.

NoteWhy do I use list comprehensions?

To create a list containing the outcome of an action repeated over an iterable’s items (see Snippet 4.38, line 14).

NoteHow do I create list comprehensions?

We include a Python statement containing a for clause among brackets (see Snippet 4.38, line 12).

# the for loop way
# --+ create an empty list
L = []
# --+ create a for loop appending the square of some items
>>> for i in range(3):
...    L.append(i ** 2)
# --+ print the list
>>> print(L)
[0, 1, 4]

# the list comprehension way
>>> L = [i ** 2 for i in range(3)]
>>> print(L)
[0, 1, 4]
NoteHow do I implement a nested for loop in list comprehensions?

As Snippet 4.39 shows, a nested for loop becomes a one-liner in a list comprehension. The first for clause in line 7 would correspond to the outer for loop reported in Snippet 4.36, whereas the second for clause in line 7 would correspond to the inner for loop reported in Snippet 4.36.

# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]

# implementing a nested for loop with a list comprehension
>>> LETTER2COLOR = ["{} <-> {}".format(i, j) for i in LETTERS for j in COLORS]
['x <-> blue',
 'x <-> green',
 'x <-> red',
 'y <-> blue',
 'y <-> green',
 'y <-> red',
 'z <-> blue',
 'z <-> green',
 'z <-> red']
NoteCan I use the zip generator within a list comprehension?

Yes, we can. To do that, the for clause must consider two iterables simultaneously (see Snippet 4.40, line 6).

# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]

# implementing a nested for loop with a list comprehension
>>> LETTER2COLOR = ["{} <-> {}".format(i, j) for i, j in zip(LETTERS, COLORS)]
['x <-> blue', 'y <-> green', 'z <-> red']
NoteCan I embed control flow in a list comprehension?

Yes, we can. To do that, the for clause must be preceded by an if statement and, at least, an else statement (see for example Snippet 4.40’s line 22).

# import the function log from math
from math import log

# the object to manipulate
>>> L1 = [0, 1, 2]

# the for loop way
# --+ the empty list
L2 = []
# --+ the for loop appending the log of some items
>>> for i in L1:
...     if i > 0:
...         L2.append(log(i))
...     else:
...         L2.append(log(i + 0.001))
# --+ print the list
>>> print(L2)
[-6.907755278982137, 0.0, 0.6931471805599453]

# the list comprehension way
# --+ the list comprehension is a one-liner!
>>> L2 = [log(i) if i > 0 else log(i + 0.001) for i in L1]
# --+ print the list
>>> print(L2)
[-6.907755278982137, 0.0, 0.6931471805599453]