Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are parentheses required around a tuple?

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 
like image 294
wim Avatar asked Apr 15 '13 14:04

wim


People also ask

Does tuple need parenthesis?

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.

How do you make a tuple without parentheses in Python?

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.

Why do you need parentheses in Python?

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.

What brackets are used in tuple?

A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.


1 Answers

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) 
like image 59
ecatmur Avatar answered Sep 30 '22 18:09

ecatmur