Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator expressions and brackets

why are brackets, specifically parentheses, necessary for generator expressions which contain tuples?

Why

((x, y)
 for x in range(10)
 for y in range(20))

instead of

(x, y
 for x in range(10)
 for y in range(20))

SyntaxError: invalid syntax
like image 930
Har Avatar asked May 13 '26 13:05

Har


1 Answers

The latter is kind of ambiguous: It starts like a normal tuple, but then turns out to be a generator later in the parse. Maybe this becomes more apparent if we have more than two elements, as in (1, 2, 3, 4, x for x in range(10)).

This can also be seen in the grammar specification:

generator_expression ::=  "(" expression comp_for ")"

Where expression later boils down to atom (among others)

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display
               | generator_expression | dict_display | set_display
               | string_conversion | yield_atom
parenth_form ::=  "(" [expression_list] ")"
expression_list ::=  expression ( "," expression )* [","]

I.e., an expression_list like x, y has to be enclosed in parentheses (except in an assignment, like a = b, c, where it can be used directly).

assignment_stmt ::=  (target_list "=")+ (expression_list | yield_expression)

(Not just for generators, also for list comprehensions, and also in Python 3.)

like image 177
tobias_k Avatar answered May 15 '26 04:05

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!