GOTCHA with list comprehension

Marko Rauhamaa marko at
Wed Aug 5 13:10:13 CEST 2015

Chris Angelico <rosuav at>:

> On Wed, Aug 5, 2015 at 7:01 PM, Marko Rauhamaa <marko at> wrote:
>> Chris Angelico <rosuav at>:
>>> 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).


More information about the Python-list mailing list