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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With