GOTCHA with list comprehension

Chris Angelico rosuav at gmail.com
Wed Aug 5 03:20:05 EDT 2015


On Wed, Aug 5, 2015 at 5:03 PM, Pavel S <pavel at schon.cz> wrote:
> 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 ]

Yep. A chain of 'if' clauses isn't materially different from a single
'if' with a bunch of 'and' checks, but if you alternate 'if' and 'for'
clauses, you get a comprehension that conditionally nests its
iterations.

ChrisA



More information about the Python-list mailing list