luky
luky

Reputation: 2370

python tuple ending with comma difference

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

Upvotes: 0

Views: 641

Answers (4)

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

Upvotes: 0

kiranr
kiranr

Reputation: 2465

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

Upvotes: 3

Danis
Danis

Reputation: 344

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

Upvotes: 1

Ibrahim Almahfooz
Ibrahim Almahfooz

Reputation: 317

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.

Upvotes: 1

Related Questions