pythonprintftuplesconvention

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,)

Solution

  • 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'>.