Hacker Newsnew | comments | show | ask | jobs | submitlogin

I think this is great, I've been doing Python for a while and I knew many of the features but I also learned a few new ones.

I don't understand how this one to flatten lists works:

    a = [[1, 2], [3, 4], [5, 6]]
    [x for l in a for x in l]
Can somebody explain what the order of operations is here and what the variables refer to in the various stages of evaluation?



So that flattening can also be written as:

    x = [[1,2], [3,4], [5,6]]
    [x for x in x for x in x]
More perversely, we can also flatten with my invention:

    list(None for x in x if (yield from x) and False) # Python >=3.3
More reasonably, of course,

    list(itertools.chain.from_iterable(x))

-----


The expression is a list comprehension with 2 nested for statements. It is similar to this, which names its result:

   result = []
   for l in a:
      for x in l:
         result.append(x)

-----


Yes. And the order of the two for's in the list comprehension was deliberately kept the same as the order of the two for loops in your explicit code, on purpose, for ease of remembering how the former (i.e. list comp) works.

-----


That order is the part that confused me. I expected to read it right-to-left, instead it's left to right for the for statements, then the expression on the left at the end.

I see now that the Python docs explain this very clearly...

-----


Yes. Meant to say that but forgot - that the Python docs explain it. That's where I read it myself :)

-----




Applications are open for YC Summer 2015

Guidelines | FAQ | Support | API | Lists | Bookmarklet | DMCA | Y Combinator | Apply | Contact

Search: