by matt_wulfeck · 10y ago · 0 comments
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.
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.
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.