What is the difference between
("a")
and
("a",)
I noticed that for example mysql wrapper parameters formatting doesn't work with the first case, it must end with comma.
cursorA.execute(query, (url,))
4 Answers 4
if you write only one element in parentheses (), the parentheses () are ignored and not considered a tuple.
x = ("a")
print(type(x))
output: str
to generate a one-element tuple, a comma , is needed at the end.
x = ("a", )
print(type(x))
ouput : tuple
Comments
The First will create a string and the second will make a tuple. That's actually the difference between making a tuple and a string between two parentheses.
Comments
when using only parentheses, you are not creating a tuple, because the interpreter treats this as increasing operator precedence (just like parentheses in mathematics), and if you put a comma, the interpreter will understand that we are trying to create a tuple with one element, and do not increase priority
Comments
This code below which is not "Tuple" is :
x = ("a") # Is not Tuple
Same as this code below:
x = "a"
While this code below is "Tuple":
("a",) # Is Tuple
("a")is not a tuple at all, it is just"a". The parentheses have no semantic meaning other than determining scope and precedence. The comma makes the tuple.tuple, which is(), requiring the parentheses and prohibiting commas. But yes, in all other cases, the parentheses are only needed for disambiguation/grouping, they're not what defines atuple.