Linux/Unix > Python Essential Reference, Second Edition > 6. Functions and Functional Programming > List Comprehensions | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104017178092175082019016

### 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 sequence1
                for item2 in sequence2
                ...
                for itemN in sequenceN
                if condition]

This syntax is roughly equivalent to the following code:

    s = []
    for item1 in sequence1:
        for item2 in sequence2:
            ...
               for itemN in sequenceN:
                   if condition: s.append(expression)

To illustrate, consider the example in Listing 6.1:

##### Listing 6.1 List Comprehensions

    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]          #      (7,'a'),(7,'b'),(7,'c'),
                                  #      (8,'a'),(8,'b'),(8,'c')]

    f = [(1,2), (3,4), (5,6)]
    g = [math.sqrt(x*x+y*y)       # f = [2.23606, 5.0, 7.81024]
         for x,y in f]

    h = reduce(lambda x,y: x+y,   # Sum of squares
               [math.sqrt(x*x+y*y)
                for x,y in f])

The sequences supplied to a list comprehension don’t have to be the same length because they’re iterated over their contents using a nested set of `for` loops, as previously shown. The resulting list contains successive values of expressions. The `if` clause is optional; however, if it’s used, `expression` is evaluated and appended to the result only if `condition` is true.

If a list comprehension is used to construct a list of tuples, the tuple values must be enclosed in parentheses. For example, `[(x,y) for x in a for y in b]` is legal syntax, whereas `[x,y for x in a for y in b]` is not.

Finally, it is important to note that the variables defined within a list comprehension are evaluated within the current scope and remain defined after the list comprehension has executed. For example, in `[x for x in a]`, the iteration variable `x` overwrites any previously defined value of `x` and is set to the value of the last item in `a` after the list is created.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.