Is there a reference somewhere defining precisely when enclosing tuples with parentheses is or is not required?
Here is an example that surprised me recently:
>>> d = {} >>> d[0,] = 'potato' >>> if 0, in d: File "<stdin>", line 1 if 0, in d: ^ SyntaxError: invalid syntax
Creating a TupleThe parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). A tuple can also be created without using parentheses.
You can print a tuple without parentheses by combining the string. join() method on the separator string ', ' with a generator expression to convert each tuple element to a string using the str() built-in function.
Parentheses are necessary when you want to invoke functions. Calling on the name of a function without following it by parentheses will point towards the function object, but will not call the function itself. The code inside the body of the function will not get executed.
A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With