Joe
Joe

Reputation: 1619

What's the reason for the ordering of for statements in a nested list comprehension

This question describes how to use list comprehensions to flatten a nested structure, like so: [leaf for tree in forest for leaf in tree]

As John Mee mentions in the comments, this would be clearer if the order of the for statements was reversed, like so: [leaf for leaf in tree for tree in forest]

Why are for loops in Python's list comprehensions interpreted in this order?

Upvotes: 3

Views: 188

Answers (2)

englealuze
englealuze

Reputation: 1663

Because the first one is better mapping to the for loop code it represented

[leaf *for tree in forest for leaf in tree*]
                      |
                      V
            for tree in forest:
                for leaf in tree:
                      |
                      V
               expected result

while the second one is in this sense not valid

[leaf *for leaf in tree for tree in forest*]
                      |
                      V
            for leaf in tree:
                for tree in forest: 
                      |
                      V
                     ???

Upvotes: 2

Patrick Haugh
Patrick Haugh

Reputation: 60974

The idea is to mimic nested for loops.

[x for y in z for x in y]

is organized in the same order as

for y in z:
    for x in y:
        yield x

This is mentioned in PEP 202 - List Comprehensions

The form [... for x... for y...] nests, with the last index varying fastest, just like nested for loops.

Upvotes: 5

Related Questions