Notes for the article Python List Comprehensions: Explained Visually by Trey Hunner
Integrated with loops
In [1]:
list_with_for_loop = [x for x in range(10)]
print list_with_for_loop
Even with conditions in the for loop
In [2]:
list_with_for_loop_conditional = [x for x in range(10) if x%2 == 1]
print list_with_for_loop_conditional
Nested loops in a list
In [3]:
list_with_nested_loops = [ [x, y] for x in range(3) for y in range(3) ]
print list_with_nested_loops
Another example of nested loops
In [4]:
list_with_nested_loops_2 = [ x for x in range(y) for y in range(3)]
print list_with_nested_loops_2
The article gives an example of how to flatten a matrix using this trick. Semantically, one would using
In [5]:
matrix = [[11,12],[21,22]]
row = [1,2]
wrong_flatten_of_matrix = [x for x in row for row in matrix]
print "matrix is", matrix
print "flattened matrix is", wrong_flatten_of_matrix
which is obviously WRONG. The correct code is given by the author as
In [6]:
right_flatten_of_matrix = [x for row in matrix for x in row]
print "matrix is", matrix
print "flattened matrix is", right_flatten_of_matrix
The key is to write the nested loops in a list as the normal nested loops.
With this possible confusion, the author proposed a line breaking solution
In [7]:
right_flatten_of_matrix_line_breaking = [
x
for row in matrix
for x in row
]
print "matrix is", matrix
print "flattened matrix is", right_flatten_of_matrix_line_breaking
which significantly improved the readability.