Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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',).

like image 662
Avadhesh Avatar asked Sep 20 '10 10:09

Avadhesh


People also ask

Why does tuple add a comma?

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.

What does a trailing comma do in Python?

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 do you remove a trailing comma from a tuple?

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!

What does a comma after a variable mean in Python?

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.


2 Answers

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

like image 115
Ben James Avatar answered Sep 30 '22 19:09

Ben James


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.

like image 44
Philipp Avatar answered Sep 30 '22 19:09

Philipp