This is an old revision of the document!
List Comprehensions
List comprehensions are used for creating lists from existing lists and other iterable structures. List comprehensions typically follow formatting similar to set-builder notation in discrete mathematics.
Syntax
Consider the following illustrative Python3 example for generating a list of squares:
>>> sq = []
>>> for i in range(10):
... sq.append(i**2)
...
>>> sq
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The same could be achieved in the following list comprehension1)
>>> [i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Multiple Loops
Note that this basic syntax is easily extended to multiple loops and variables:
>>> [(x**2, y**2) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 4), (1, 0), (1, 1), (1, 4), (4, 0), (4, 1), (4, 4)]
Examples
Conditionals:
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1,3), (1,4), (2,3), (2,1), (2,4), (3,1), (3,4)]
Repetitions:
>>> [i for i in range(1, 5) for j in range(i)]
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Processing non-range() iterables:
>>> vec = [-4, -2, 0, 2, 4]
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
Flattening a double list:
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]