4 ms·
But what do you gain from using nested list comprehension like that? There's no performance gain (or very, very little). The only tangible benefit I see is savi
by matt_wulfeck 11y ago
But what do you gain from using nested list comprehension like that? There's no performance gain (or very, very little). The only tangible benefit I see is saving a few lines of code.
And for those few lines of code you've traded the ability for new programmers to understand it easily. To me that's a net loss.
- spamizbad 11y agofor-ins leak iteration variables into the function scope, which can introduce subtle bugs if you're not careful. set/dict/generator comprehensions do not. Example: for foo in bar: baz(foo) print foo # Will actually print something Whereas whatever = {baz(foo) for foo in bar} print foo # NameError: name 'foo' is not defined does not put foo into the outer scope. list comprehensions in python 2 (but not 3) will leak variables however.
- orf 11y agoThere is always a performance gain, and sometimes it can be fairly huge.
- Retra 11y agoNew programmers should learn how to use list comprehensions. They're not just some obscure Python concept, they appear in multiple other languages, as well as mathematics.
- RodericDay 11y agoIt's actually much more sensible code a lot of the time, especially for people who didn't get a degree that consisted of a lot of for-looping in class. good_jedis = [jedi for jedi in universe if jedi.alignment == "good"] vs. good_jedis = [] for jedi in universe: if jedi.alignment == "good": good_jedis.append(jedi) And then when you get on stuff like dictionary comprehensions and generator expressions, it starts becoming an amazing tool that is able to accomplish things that are straight-up cumbersome with old loops. There's a computer science course out there that a friend was telling me about, that begins by showing students how to "map" a function over an iterable, way way before a "for loop" ever shows up. I think this is the way it should be done, "for loops" as a three-line-structure only seem natural to people who grew up programming for loops.