I have no problem understanding this:
a = [1,2,3,4] b = [x for x in a]
I thought that was all, but then I found this snippet:
a = [[1,2],[3,4],[5,6]] b = [x for xs in a for x in xs]
Which makes b = [1,2,3,4,5,6]
. The problem is I’m having trouble understanding the syntax in [x for xs in a for x in xs]
, Could anyone explain how it works?
Advertisement
Answer
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.