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.
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.
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).
The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With