Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python treat a tuple with one item as an integer? [duplicate]

Tags:

python

tuples

See the following example:

(1) #outputs 1

But if I add the comma, it will be right according to the Python docs:)

(1,) #output (1,)

That's super odd to me. Can anyone explain this?

A related question: Is there not a way for Python to know when (1) should be a tuple (1,) instead of 1?

Thanks for future replies.

like image 710
user2228392 Avatar asked Dec 14 '13 13:12

user2228392


1 Answers

Actually, it's the comma that creates a tuple; the parentheses are only necessary in cases where there would be an ambiguity otherwise. After all, parentheses can be used for grouping as well:

>>> 1, 2
(1, 2)
>>> 1,
(1,)
>>> (1)
1
>>> 2 * 3, 4
(6, 4)
>>> 2 * (3, 4)
(3, 4, 3, 4)
>>> 1, + (2, 3) * 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'tuple'
>>> (1,) + (2, 3) * 4
(1, 2, 3, 2, 3, 2, 3, 2, 3)
like image 123
Tim Pietzcker Avatar answered Oct 17 '22 08:10

Tim Pietzcker