GOTCHA with list comprehension

Pavel S pavel at schon.cz
Wed Aug 5 08:48:55 CEST 2015


Hi,

I recently found interesting GOTCHA while doing list comprehension in python 2.6:

>>> values = ( True, False, 1, 2, 3, None )
>>> [ value for value in values if value if not None ]
[True, 1, 2, 3]

I was wondering why this list comprehension returns incorrect results and finally found a typo in the condition. The typo wasn't visible at the first look.

My intention was: if value is not None
But I wrote: if value if not None

Is that a language feature of list comprehension that it accepts conditions like: if A if B if C if D ...?


More information about the Python-list mailing list