How to read aloud Python List Comprehensions?

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)

Example #1

[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]


Example #2

[[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

Leave a Comment