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',)
.
The reason why you need a comma , for a tuple with one element is that "tuple is an object delimited by comma , ", not "an object enclosed in parentheses () ". Note that it is actually the comma which makes a tuple, not the parentheses.
It helps to eliminate a certain kind of bug. It's sometimes clearer to write lists on multiple lines. But in, later maintenace you may want to rearrange the items. But if you allow trailing commas, and use them, you can easily rearrange the lines without introducing an error.
How can I remove the comma from each tuple in the list. You can't; that's the syntax for a one-tuple (the comma is the key, not the parentheses). Why would you want to, anyway? Type this into the Python shell: [(1), (2), (3), (5), (4)] and look at what you get -- then you'll see why the question makes no sense!
In Python, it's the comma that makes something a tuple: >>> 1 1 >>> 1, (1,) The parenthesis are optional in most locations. python. Follow this question to receive notifications.
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.
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