When are parentheses required around a tuple?

The combining of expressions to create a tuple using the comma token is termed an expression_list. The rules of operator precedence do not cover expression lists; this is because expression lists are not themselves expressions; they become expressions when enclosed in parentheses.

So, an unenclosed expression_list is allowed anywhere in Python that it is specifically allowed by the language grammar, but not where an expression as such is required.

For example, the grammar of the if statement is as follows:

if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

Because the production expression is referenced, unenclosed expression_lists are not allowed as the subject of the if statement. However, the for statement accepts an expression_list:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

So the following is allowed:

for x in 1, 2, 3:
    print(x)

Leave a Comment