[ x for x in xrange(10) when p(x) ]

Peter Hansen peter at engcorp.com
Thu Nov 10 07:26:31 EST 2005


bonono at gmail.com wrote:
> Alex Martelli wrote:
> 
>>This becomes a valid list comprehension by writing 'if' instead of
>>'when'.
> 
> valid, yes. efficient, I am not sure.
> 
> [ x for x in xrange(10000000) if p(x) ]
> 
> means I need to go through the whole range even if p = lambda x: x < 2.

If you're looking for efficient, not to mention readable, then this is 
obviously far superior:

   [x for x in xrange(2)]

or even

   [0, 1]

Yes, I know yours was a contrived example, but there's a time when 
contrived examples stop showing us anything useful.

Do you have a real use case, where you think that the list comprehension 
form is more readable or somehow better, and yet you are concerned about 
its failure to magically optimize your case?

(I say "readable or somehow better" since you stated in another post "I 
just try to use list/generator expression when possible" but you didn't 
explain your reason for doing so.  I assume you have some reason other 
than arbitrary whim.)

-Peter



More information about the Python-list mailing list