GOTCHA with list comprehension

Pavel S pavel at schon.cz
Wed Aug 5 09:03:29 CEST 2015


It seems this is allowed by the grammar:

list_display        ::=  "[" [expression_list | list_comprehension] "]"
list_comprehension  ::=  expression list_for
list_for            ::=  "for" target_list "in" old_expression_list [list_iter]
old_expression_list ::=  old_expression [("," old_expression)+ [","]]
old_expression      ::=  or_test | old_lambda_expr
list_iter           ::=  list_for | list_if
list_if             ::=  "if" old_expression [list_iter]

So chaining multiple ifs is fine:

[ i for i in range(10) if True if True if True if True ]

Dne středa 5. srpna 2015 8:49:20 UTC+2 Pavel S napsal(a):
> 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