Why are parentheses needed in tuples?

Some time ago I thought that the tuple constructor is a pair of parentheses () .

Example:

 >>> (1, ) (1, ) >>> type((1, )) <type 'tuple'> >>> t = (1, ) >>> type(t) <type 'tuple'> 

But now I know that it is a comma,.

So, doing the same as above:

 >>> 1, (1,) >>> type(1,) <type 'int'> # Why? >>> 1,2,3 (1,2,3) 

But if I do this:

 >>> type(1,2,3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type() argument 1 must be string, not int 

This makes sense to me, but:

 >>> t = 1,2,3 >>> type(t) <type 'tuple'> 

And finally:

 >>> type((1,2,3)) <type 'tuple'> 

Here's the question: why do we need parentheses in the latter case, if the tuple is just 1,2,3 ?

+5
source share
5 answers

Because sometimes without parentheses the expression will be ambiguous: without them, you call a function call with three arguments. Since some functions need to take three arguments, another representation is required in order to express one three-element argument of the tuple. As it happens, type() can be called with one or three arguments. In the latter case, the first argument must be the name of the class, so it complains when it sees an integer.

+1
source

In some contexts, commas have a different meaning - for example, inside function call parentheses, they separate parameters. Placing a set of parentheses around your tuple ensures that it is in a simple expression context where commas are interpreted as separators of code elements.

+4
source

I would say that t is (1,2,3):

 >>> t = 1,2,3 >>> t (1, 2, 3) >>> type(t) <class 'tuple'> 

And this t = 1,2,3 is syntactic sugar for the explicitly bracketed version, a form of sugar that is especially good for unpacking.

+3
source

You call type with three ints, which does not match the expected arguments for the overloaded implementation.

+1
source

Since the type () function will be interpreted without parentheses, you will be given three parameters, not one.

According to the official python documentation , type () can take one or three parameters:

  • type (object)
  • type (name, base, dict)

And in brackets you specify only one parameter - the tuple object, which does not cause an error.

+1
source

All Articles