GOTCHA with list comprehension

Peter Otten __peter__ at web.de
Wed Aug 5 09:04:51 CEST 2015


Pavel S wrote:

> 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 ...?

I think it's just that a condition may be a constant expression. Python 
evaluates (not None) for every item in values. Other variants:

>>> if 42:
...     print("branch always taken")
... 
branch always taken
>>> always_yes = "yes" if True else "no"
>>> always_yes
'yes'
>>> [c for c in "foo" if "true in a boolean context"]
['f', 'o', 'o']

An optimizer might detect that (not None) is always True in a boolean 
context, but that would be an implementation detail.





More information about the Python-list mailing list