COMP 200 Resources

[Rice University]

List Comprehensions

List comprehensions are a convenient way to declaratively define lists in terms of a process.    List comprehensions are really nothing more than short-cuts to writing loops to define and fill lists with values.

The basic syntax for a list comprehension is

[ expression for expr in sequence]

Where

Examples:

# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] can be made by
[x for x in range(10)]   

# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] can be made by
[x**2 for x in range(10)]  

# [(-2, 0.25), (3, 27), (-1, -1.0), (-2, 0.25), (5, 3125)] can be made by
[(x, x**x) for x in [-2, 3, -1, -2, 5]]

For creating more complex lists, the general syntax for list comprehensions is

[ expression for expr in sequence1
             for expr2 in sequence2 ...
             for exprN in sequenceN
             if condition ]

Where

Examples:

# [(0, -2), (0, -3), (1, -2), (1, -3), (2, -2), (2, -3), (3, -2), (3, -3), (4, -2), (4, -3)] can be made by
[(x,y) for x in range(5)  
    for y in [-2, -3]]   

# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] can be made from
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

 

References