Explanation of how nested list comprehension works?

b = [x for xs in a for x in xs] is similar to following nested loop.

b = []
for xs in a:
   for x in xs:
       b.append(x)

if a = [[1,2],[3,4],[5,6]], then if we unroll that list comp, we get:

      +----------------a------------------+ 
      | +--xs---+ , +--xs---+ , +--xs---+ | for xs in a
      | | x , x |   | x , x |   | x , x | | for x in xs
a  =  [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]
b  =  [ x for xs in a for x in xs ] == [1,2,3,4,5,6] #a list of just the "x"s

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.

Tags:

Python

List