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
- expression -- any Python expression that results in a value. In general, this expression would involve expr.
- expr -- a variable name to indicate a single value from sequence.
- sequence -- any Python expression the results in an iterable entity, e.g. list, tuple.
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
- For every element in sequence1, every element in sequence2 is run and for every element in sequence2, every element in sequence3 is run, etc., etc..
- expression is only calculated if condition is True.
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]