February 2006
Intermediate to advanced
648 pages
14h 53m
English
Many operations involving map() and filter() can be replaced with a list-construction operator known as a list comprehension. The syntax for a list comprehension is as follows:
[expression for item1 in iterable1
for item2 in iterable2
...
for itemN in iterableN
if condition ]
This syntax is roughly equivalent to the following code:
s = []
for item1 in iterable1:
for item2 in iterable2:
...
for itemN in iterableN:
if condition: s.append(expression)
To illustrate, consider the following example:
a = [-3,5,2,-10,7,8] b = 'abc' c = [2*s for s in a] # c = [-6,10,4,-20,14,16] d = [s for s in a if s >= 0] # d = [5,2,7,8] e = [(x,y) for x in a # e = [(5,'a'),(5,'b'),(5,'c'), for y in b # (2,'a'),(2,'b'),(2,'c'), if x > 0 ] # ...