Why does adding a trailing comma after a variable name make it a tuple?
I want to know that why adding a trailing comma after a variable name (in this case a string) makes it a tuple
. i.e.
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
When I print abc
it returns the tuple
('mystring',)
.
It is the commas, not the parentheses, which are significant. The Python tutorial says:
A tuple consists of a number of values separated by commas
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
See the Python Tutorial section on Tuples and Sequences
Because this is the only way to write a tuple literal with one element. For list literals, the necessary brackets make the syntax unique, but because parantheses can also denote grouping, enclosing an expression in parentheses doesn't turn it into a tuple: you need a different syntactic element, in this case the comma.