List Comprehensions

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 ] # ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.