Multiple Element Tuples
In Python, multiple-element tuples look like:
1,2,3
...
but again, it is the commas, not the parentheses, that define the tuple.
Oh, really?!
Then why:
>>> tuple((((((1, 2, 3)))))) # creates a valid tuple
# (1, 2, 3)
>>> tuple(1, 2, 3, ) # But not here
# TypeError: tuple() takes at most 1 argument (3 given)
More seriously, I don't get why the parenthesis was not chosen over the commas?
Because I think it would create a paradox when:
>>> 1, # is a valid tuple
# (1,)
>>> tuple([1]) # Or this
# (1,)
>>> tuple(1) # But not this one
# TypeError: 'int' object is not iterable
However, if you consider that parenthesis were always in charge of instantiating a tuple, all of the problems with instantiating tuple with multiple items are gone.
e.g. in my imaginary world:
>>> (1, 2, 3) # stay valid
# (1, 2, 3)
>>> (1) # is newly valid
# (1)
>>> () # stay valid
# ()
>>> 1,
# TypeError: int() takes exactly 1 argument (2 given)
I know this is a well-known feature and I'm already sorry if it a duplicate. I have found lots of similar topics about how tuple worked, but none explaining in details why this feature was created like that.
I am also aware that this topic could be closed as opinion-based, but I am mostly interested in technical reasons (if any), or at least historical reasons.
Thank you
解决方案
This is an artifact of the grammar.
The terms separated by commas are a building block for tuples, lists, and sets depending on whether they are wrapped by square brackets, curly braces, or nothing at all.
The chief challenge when specifying a grammar is balancing multiple competing uses of the same characters. Commas separate parts of lists, tuples, dicts, and sets. Commas also separate arguments in function calls. Trailing commas are allowed for both uses (and are required for tuples of length one). Likewise, parentheses have multiple uses including function calls and grouping for arithmetic expressions. The period serves as a decimal point and for the getattribute operator.