3 ms·
> FWIW, I don't think I've ever seen an example where the cleanest (list | generator) comprehension is less clear than the cleanest equivalent for loop. I don'
by LyndsySimon 9y ago
> FWIW, I don't think I've ever seen an example where the cleanest (list | generator) comprehension is less clear than the cleanest equivalent for loop. I don't believe one exists.
Interesting. I'm not sure if I agree or disagree.
I think the primary benefit of a comprehension is that it can be considered as a "unit", and you don't have to think about the iteration as fully to understand what's happening. As soon as "what's happening" gets more than minimally complex, that advantage is lost. Generator comprehensions should be much more clear and concise than their equivalent implementations using generator functions, though.
If I remember this evening, I'm going to go through my code library and see if I can find something that will satisfy your challenge :)
- crdoconnor 9y agoI consider it an instance of https://en.wikipedia.org/wiki/Rule_of_least_power https://en.wikipedia.org/wiki/Rule_of_least_power List comprehensions are less expressive than for loops hence there is less to reason about. Hence, if what you want is achievable with a list comprehension, its intent will naturally be clearer than the for loop equivalent. ...provided you don't make it intentionally obtuse like the OP did.