Skip to main content

Python micro-ideas : Does tuple require parentheses as a must?

The answer is No.

This has tripped many Python developers, many times. I have come across this once again while answering this question on Stack Overflow.

The OP (Original Poster) asked:

I noticed by accident that Python's primitive math operators support commas in both numeric arguments. A tuple is returned. What is it doing and why is this syntax supported?

Here are a few examples:

>>> 2,10,2 / 2
(2, 10, 1)

>>> 2,10,2 * 2
(2, 10, 4)

>>> 2,10,2 % 2,3
(2, 10, 0, 3)

while the question is misleadingly put as a mathematical operator and operation related question, but the OP is clearly confused about tuple syntax (and operator precedence).

My answer was:

In 2,10,2 / 2, the operation performed actually is:

2, 10, (2 / 2)

Hence you get the (2, 10, 1) as output.

In Python, tuples are actually a collection of values separated by commas, the surrounding parentheses are to avoid ambiguity.

Hope the answer clarifies the confusion.

Happy coding.


Comments powered by Disqus