[Python-3000] The order of list comprehensions and generator expressions

Noam Raphael noamraph at gmail.com
Sun Sep 16 21:01:29 CEST 2007


On 9/16/07, Guido van Rossum <guido at python.org> wrote:
> I think it's not so obvious that reversing the order is any better
> when you throw in some if clauses:
>
> [friend for city in cities if city.name != "Amsterdam" for friend in
> city.friends if friend.name != "Guido"]
>
> vs.
>
> [friend for friend in city.friends if friend.name != "Guido" for city
> in cities if city.name != "Amsterdam"]
>
> --Guido
>

I think that it's still better, at least if you add some newlines:

[friend
(Ok, we are talking about a list of friends. From where do these
friends come from?)
for friend in city.friends if friend.name != "Guido"
(Ah, they are all the friends in a city who aren't called Guido. What
about the city?)
for city in cities if city.name != "Amsterdam"]
(Ah, the city is every city which isn't Amsterdam.)

Versus:

[friend
(Ok, we are talking about a list of friends. From where do these
friends come from?)
for city in cities if city.name != "Amsterdam"
(What do cities which aren't Amsterdam have to do with my friend?)
for friend in city.friends if friend.name != "Guido"]
(Ah, we're talking about all the friends in those cities who aren't
called Guido. Let's have a look at the first line to remember what we
do with them... ah, yes, we just return them...)

Noam


More information about the Python-3000 mailing list