Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)

Chris Angelico rosuav at gmail.com
Mon Mar 24 01:04:51 EDT 2014


On Mon, Mar 24, 2014 at 3:14 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> Neat! So I play around... Change it to
> [(x,y) for x in range(1,10000) for y in range(1,10000)]
> and I dont have an answer but a thrashing machine!! (*)

Yes, because you used square brackets, which means that the list has
to be fully realized. As you comment, range changed from returning a
list to returning an iterable, and this action is similarly cheap:

>>> ((x,y) for x in range(1,10000) for y in range(1,10000))
<generator object <genexpr> at 0x7f53ed61b360>

You can take a few elements from that cheaply:

>>> [next(_),next(_),next(_)]
[(1, 1), (1, 2), (1, 3)]

If you like thinking in "lazy lists", you can probably think just as
easily with generators; you can't pull up arbitrary elements from it,
or query its length, but for many purposes a generator will do.

ChrisA



More information about the Python-list mailing list