0

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,))
asked Feb 12, 2021 at 17:55
2
  • 3
    ("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. Commented Feb 12, 2021 at 17:59
  • @user2390182: Aside from the special case of the empty 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 a tuple. Commented Nov 19, 2021 at 16:04

4 Answers 4

3

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

answered Feb 12, 2021 at 18:00
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Feb 12, 2021 at 18:03

Comments

1

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

answered Feb 12, 2021 at 18:08

Comments

0

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
answered May 21, 2022 at 13:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.