When are parentheses required around a tuple?

tuple
tuple attributes
tuple unpacking
python tuple remove trailing comma
slicing tuples
use of tuple in python
python tuple methods
functions of tuple in python

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

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)

When are parentheses required around a tuple?, Which sequence data type is defined by enclosing the elements in parentheses ()? parenthesis around a tuple of literals in a for. Skaperen Reputation: 13 Likes received: 104 #1. Aug-24-2019, 11:02 PM . is parenthesis required around a tuple of

Python Tutorial: Sequential Data Types, to denote code blocks as they are in many "C-like" languages. And so, if you want to define a one-element tuple, you must use a comma: In [12]: t = (10,) In [13]: type(t) Out[13]: tuple Generator expressions. Finally, we can use round parentheses to create “generators,” using what are known as “generator expressions.”

Parentheses are also required when you want to avoid ambiguity.

The following are two different expressions... just because something is an 'expression list', doesn't result in the expression list you might expect :)

(1, 2, 3) + (4, 5) # results in (1, 2, 3, 4, 5) because + does sequence.extend on the tuples
1, 2, 3 + 4, 5     # this results in (1, 2, 7, 5) because + adds the elements, since there were no parentheses to protect the separate tuples

What is the meaning of curly braces?, have values between parentheses ( ) separated by commas , . Tuples are frequently used for multiple return values. Much of the standard library, including two of the functions of the iterable interface (next and done), returns tuples containing two related but distinct values. The parentheses around tuples can be omitted in certain situations, making multiple return values easier to implement.

Tuples in Python 3, The most important thing you need to know about tuples is that you have to take So you need parentheses around the tuple values, but you also need to close  A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The 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.).

Mission Python: Code a Space Adventure Game!, As usual, let's start an interactive session to explore tuples at work. Because parentheses can also enclose expressions (see Chapter 5), you need to do  The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'. CS8124: Error: Tuple must contain at least two elements. CS8125: Error: Tuple element name '{0}' is only allowed at position {1}. CS8126: Error: Tuple element name '{0}' is disallowed at any position. CS8127: Error: Tuple element

Learning Python: Powerful Object-Oriented Programming, Lists are enclosed in square brackets ( [ and ] ) and tuples in parentheses ( ( and ) Also, it is required to include a comma when specifying a tuple with only one  The new syntax for tuples mirrors the syntax for input parameters: a comma separated list of variable declarations inside parentheses. For example, here is the signature for a find method that searches the input for a match and returns a tuple containing both the index and item as output.

Comments
  • I find it especially interesting that for k, in d: print k does work in that case.
  • The Python grammar will show you what is allowed, for example, in an if 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.
  • ...I fail to understand how you could have been surprised by the for failing with 0,... python identifiers must start with a (unicode)letter or underscore and 0 is not a valid python identifier hence I would have expected a SyntaxError there.
  • That's why David said for k, not for 0, (It works i.e. it successfully does tuple unpacking into k for the case where the dict keys are 1-element tuples)
  • +1 That certainly explains why for k, in d works (because for k, v in d works).
  • Question: Should you write it for x in 1, 2, 3: or for x in (1, 2, 3):? I've always written it the second way, but that was because I didn't know the first way was valid until just now when I tried. Now I'm wondering if the () are unnecessary noise, or if they somehow help in reading the code. Does PEP8 provide any guidance on this?
  • @ArtOfWarfare there's no specific guidance in PEP8. It might help to compare with if statements, where parentheses are recommended only for a condition that spans multiple lines. So: for x in (1, <newline> 2, <newline> 3):.
  • Oh yeah? How about 1,2,3 + 4,5? It doesn't result in the expression list you might expect...
  • @smci what has that got to do with my answer? What outcome did you expect?
  • Because 1,2,3 + 4,5 results in the expression 1,2,7,5, which is not what a casual reader would expect, and comes from overloading + for sequence append.
  • @smci sorry, but 1, 2, 7, 5 is exactly what I'd expect. Each part between commas is an expression; the whole is an expression_list. There is no grammar rule that sums expression lists; instead + is part of one of the contained expressions (3 + 4). To add up two tuples, make two separate expressions by adding parentheses.
  • Yes I know that. However, non-Python users or people who missed the lack of trailing comma would expect a concatenated tuple 1,2,3, + 4,5, . What a difference the trailing comma makes.