Skip to content

Instantly share code, notes, and snippets.

@poros
Created October 4, 2015 14:47
Show Gist options
  • Save poros/d66a00dc61fea307cfb7 to your computer and use it in GitHub Desktop.
Save poros/d66a00dc61fea307cfb7 to your computer and use it in GitHub Desktop.
Nested list comprehensions
matrix = [[1,2,3]] * 4
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
# FLATTEN THE MATRIX
flatten = []
for row in matrix:
for i in range(3):
flatten.append(row[i])
[row[i] for row in matrix for i in range(3)]
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
# equivalent to
from itertools import chain
list(chain(*matrix))
list(chain.from_iterable(matrix))
# TRANSPOSE THE MATRIX
[[row[i] for row in matrix] for i in range(3)]
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
# almost equivalent to
zip(*matrix)
[(1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment