Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?

Ali Afshar picture Ali Afshar · Mar 15, 2009 · Viewed 22.8k times · Source

I see this kind of thing sometimes:

(k for k in (j for j in (i for i in xrange(10))))

Now this really bends my brain, and I would rather it wasn't presented in this way.

Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?

Edit: Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.

Answer

popcnt picture popcnt · Mar 16, 2009

Check PEP 202 which was where list comprehensions syntax was introduced to the language.

For understanding your example, there is a simple rule from Guido himself:

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

Also from PEP 202, which serves to answer your question:

Rationale
    List comprehensions provide a more concise way to create lists in
    situations where map() and filter() and/or nested loops would
    currently be used.

If you had a situation like that, you could find it to be more elegant. IMHO, though, multiple nested list comprehensions may be less clear in your code than nested for loops, since for loops are easily parsed visually.