GOTCHA with list comprehension

Chris Angelico rosuav at gmail.com
Wed Aug 5 09:05:49 CEST 2015


On Wed, Aug 5, 2015 at 4:48 PM, Pavel S <pavel at schon.cz> 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 ...?

It certainly is. You can chain 'for' and 'if' clauses as much as you
like, and they behave exactly the way you'd expect. You might possibly
get a warning from a linter with your code, though, as it has an
always-true condition ("if not None" can never be false), so it's
possible something might hint at what's going on; but other than that,
all you can do is test stuff and see if it's giving the right result.

Incidentally, why Python 2.6? Python 2.7 has been out for a pretty
long time now, and if you can't move to version 3.x, I would at least
recommend using 2.7. Since the release of 2.6.9 back before Frozen
came out, that branch has been completely unmaintained. Grab yourself
a 2.7 and take advantage of some neat new features (for old values of
"new"), and improved compatibility with 3.x.

ChrisA


More information about the Python-list mailing list