Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why parenthesis are needed in tuples? [duplicate]

Tags:

python

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

Example:

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

But now I know that it is the comma ,.

So, doing the same as above:

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

But if I do:

>>> 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 are parenthesis needed in the final case if the tuple is just 1,2,3?

like image 877
Gocht Avatar asked Aug 21 '15 21:08

Gocht


People also ask

Can we create a tuple in Python without parentheses?

In Python, tuples is just a comma-separated sequence which can be created with or without parentheses () .

Why do we use double parentheses in Python?

The use of a double parentheses is actually an indicator of one of Python's coolest features - and that is that functions are themselves, objects! What does this mean? Our output is an integer, with a value of 3.

Can you have duplicates in tuples?

Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.

Does a tuple need parentheses?

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.


1 Answers

In some contexts, commas have another meaning - for example, inside the parentheses of a function call, they separate the parameters. Putting a set of parentheses around your tuple guarantees that it's in a simple expression context, where the commas are interpreted as tuple element separators.

like image 138
jasonharper Avatar answered Sep 22 '22 12:09

jasonharper