Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 264
Ali Afshar Avatar asked Mar 15 '09 22:03

Ali Afshar


People also ask

When should you use generator expressions and when should you use list comprehensions in Python?

So what's the difference between Generator Expressions and List Comprehensions? The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.

Why are lists or generator comprehensions preferred to map filter functions?

List comprehension is more concise and easier to read as compared to map. List comprehension are used when a list of results is required as map only returns a map object and does not return any list. Map is faster in case of calling an already defined function (as no lambda is required).

What is the difference between list comprehension dict comprehension and a generator?

The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.

What are the advantages of using list comprehensions?

One main benefit of using a list comprehension in Python is that it's a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. You don't have to use a different approach for each scenario.


1 Answers

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.

like image 143
popcnt Avatar answered Oct 23 '22 00:10

popcnt