O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required