Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why single element tuple is interpreted as that element in python?

Could anyone explain why single element tuple is interpreted as that element in Python?

And

Why don't they just print the tuple (1,) as (1)?

See the examples below:

>>> (1)
1
>>> ((((1))))
1
>>> print(1,)
1
>>> print((1,))
(1,)
like image 513
transang Avatar asked Jan 05 '23 01:01

transang


1 Answers

It's because (1) is not a tuple. (1) is 1 with parentheses surrounding it. As the python documentation states

it is the comma, not the parentheses, that define the tuple.

Source

The only tuple without a comma is a 0-tuple, which is (). Note, you can check this by running type((1)) and seeing that it returns <type 'int'> not <type 'tuple'>.

like image 150
Eli Sadoff Avatar answered Jan 14 '23 14:01

Eli Sadoff