Explanation of how nested list comprehension works?

Ah, the incomprehensible “nested” comprehensions. Loops unroll in the same order as in the comprehension.

[leaf for branch in tree for leaf in branch]

It helps to think of it like this.

for branch in tree:
    for leaf in branch:
        yield leaf

The PEP202 asserts this syntax with “the last index varying fastest” is “the Right One”, notably without an explanation of why.

Leave a Comment