I want to know that why adding a trailing comma after a string makes it tuple. I.e.
abc = 'mystring',
print abc
# ('mystring,)
When I print abc
it returns a tuple like ('mystring',)
.
I want to know that why adding a trailing comma after a string makes it tuple. I.e.
abc = 'mystring',
print abc
# ('mystring,)
When I print abc
it returns a tuple like ('mystring',)
.
It's just the way Python works. You can read up more about it in the documentation if you want.
Update
See above for a much better answer.
Original Answer
In python a tuple is indicated by parenthesis.
Tuples are not indicated by the parentheses. Any expression can be enclosed in parentheses, this is nothing special to tuples. It just happens that it is almost always necessary to use parentheses because it would otherwise be ambiguous, which is why the
__str__
and__repr__
methods on a tuple will show them.
I stand corrected (all I've been doing today. Sigh).
For instance:
abc = ('my', 'string')
What about single element tuples? The parenthesis notation still holds.
abc = ('mystring',)
For all tuples, the parenthesis can be left out but the comma needs to be left in.
abc = 'mystring', # ('mystring',)
Or
abc = 'my', 'string', # ('my', 'string',)
So in effect what you were doing was to create a single element tuple as opposed to a string.
The documentation clearly says:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
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.
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.