[Python-3000] The order of list comprehensions and generator expressions
noamraph at gmail.com
Sun Sep 16 19:06:29 CEST 2007
I had a thought about syntax I want to share with you.
Say you want to get a list of all the phone numbers of your friends.
You'll write something like this:
telephones = [friend.telephone for friend in friends]
Now suppose that, unfortunately, you have many friends, and they are
grouped by city. Now, you'll probably write:
telephones = [friend.telephone for friend in city.friends for city in cities]
and you'll (hopefully) get an exception, and change your line to:
telephones = [friend.telephone for city in cities for friend in city.friends]
and say, "Ah, I should've remembered this from the last time it
happened to me", and forget it until the next time it happens to you.
The reason is that the code:
for city in cities:
for friend in city.friends:
makes sense if you read it from the first line to the last line, and
makes sense if you read it from the last line to the first line, but
doesn't make a lot of sense if you start from the last line and then
jump to the first line and read it from there. In other words, you can
go from the general to the specific, and you can go from the specific
to the general, but jumping from the most specific to the most general
and back again up to the second-most specific is strange.
All this is to say that I think that the "for" parts in list
comprehensions and generator expressions should, in a perfect world,
be evaluated in the other way round.
The question remains, what should be done with the "if" parts. A
possible solution is this: only one "if" part will be allowed after
each "for" part (you don't need more than that, since you can always
use the "and" operator). So, if I want to limit the list, my line will
look like this:
telephones = [
for friend in city.friends if friend.is_really_good
for city in cities if city.is_close_to_me
What do you think?
(P.S. Please don't be annoyed at me. The answer "this will break too
much code and isn't worth it" is, of course, very sensible. I just
thought that such thoughts can be posted to this list without causing
too much harm.)
More information about the Python-3000