Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #95001

Re: GOTCHA with list comprehension

References <ebf0a31e-1021-41d2-affb-8318838a464b@googlegroups.com> <631b480d-497a-4451-9577-2788f9d4c85b@googlegroups.com>
Date 2015-08-05 17:20 +1000
Subject Re: GOTCHA with list comprehension
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1232.1438759213.3674.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Aug 5, 2015 at 5:03 PM, Pavel S <pavel@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

GOTCHA with list comprehension Pavel S <pavel@schon.cz> - 2015-08-04 23:48 -0700
  Re: GOTCHA with list comprehension Pavel S <pavel@schon.cz> - 2015-08-05 00:03 -0700
    Re: GOTCHA with list comprehension Chris Angelico <rosuav@gmail.com> - 2015-08-05 17:20 +1000
  Re: GOTCHA with list comprehension Peter Otten <__peter__@web.de> - 2015-08-05 09:04 +0200
  Re: GOTCHA with list comprehension Chris Angelico <rosuav@gmail.com> - 2015-08-05 17:05 +1000
    Re: GOTCHA with list comprehension Pavel S <pavel@schon.cz> - 2015-08-05 00:10 -0700
      Re: GOTCHA with list comprehension Chris Angelico <rosuav@gmail.com> - 2015-08-05 17:21 +1000
        Re: GOTCHA with list comprehension Pavel S <pavel@schon.cz> - 2015-08-05 00:33 -0700
    Re: GOTCHA with list comprehension Marko Rauhamaa <marko@pacujo.net> - 2015-08-05 12:01 +0300
      Re: GOTCHA with list comprehension Chris Angelico <rosuav@gmail.com> - 2015-08-05 19:52 +1000
        Re: GOTCHA with list comprehension Marko Rauhamaa <marko@pacujo.net> - 2015-08-05 14:10 +0300
      Re: GOTCHA with list comprehension Saran Ahluwalia <ahlusar.ahluwalia@gmail.com> - 2015-08-07 09:08 -0400
  Re: GOTCHA with list comprehension Laura Creighton <lac@openend.se> - 2015-08-06 06:39 +0200
  Re: GOTCHA with list comprehension Chris Angelico <rosuav@gmail.com> - 2015-08-06 14:44 +1000

csiph-web