My question is about Python List Comprehension readability. When I come across code with complex/nested list comprehensions, I find that I have to re-read t
"Construct a list of X's based on Y's and Z's for which Q is true."
I usually unfold it in my mind into a generating loop, so for example
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
is the list comprehension for the generator
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
yield (x, y)
[x for b in a for x in b]
is the comprehension for
for b in a:
for x in b:
yield x
Example result for a = [[1,2,3],[4,5,6]]
: [1, 2, 3, 4, 5, 6]
[[row[i] for row in matrix] for i in range(4)]
(note the inner expression is another comprehension!):
for i in range(4):
yield [row[i] for row in matrix]
which is unfolded
for i in range(4):
l = []
for row in matrix:
l.append(row[i])
yield l