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_list
s 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)
for k, in d: print k
does work in that case. – Notarialif
statement. You'd have to read over the full grammar to figure out where unparenthesized tuples are accepted, which is why I'm not posting this as an answer. – Exceedfor
failing with0,
... python identifiers must start with a (unicode)letter or underscore and0
is not a valid python identifier hence I would have expected aSyntaxError
there. – Honigfor k,
notfor 0,
(It works i.e. it successfully does tuple unpacking intok
for the case where the dict keys are 1-element tuples) – Marketa