GOTCHA with list comprehension

Marko Rauhamaa marko at pacujo.net
Wed Aug 5 07:10:13 EDT 2015


Chris Angelico <rosuav at gmail.com>:

> On Wed, Aug 5, 2015 at 7:01 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
>> Chris Angelico <rosuav at gmail.com>:
>>
>>> You can chain 'for' and 'if' clauses as much as you like, and they
>>> behave exactly the way you'd expect.
>>
>> How do you know what I'd expect?
>>
>> I wouldn't know what to expect myself.

> [...]

> So what would you expect nested 'if' clauses to do? Well, they become
> nested 'if' statements:
>
> primes = [n for n in range(2,24) if n%2 if n%3]
>
> primes = []
> for n in range(2,24):
>     if n%2:
>         if n%3:
>             primes.append(n)
>
> What if we have multiple 'for' loops? Same thing!

So no need to appeal to my expectations. Better just define it (as you
now did).


Marko



More information about the Python-list mailing list