Why is (5) not a tuple in Python, and how do you create a one-element tuple?
Parentheses alone only group an expression, so (5) is just the integer 5. The comma makes the tuple, so a one-element tuple is written (5,) or 5,. The empty tuple is ().
Explain it simply
In maths, (2 + 3) * 4 uses brackets only for grouping. Python reads (5) the same way: brackets around a number. What actually builds a tuple is the comma. That is why t = 1, 2, 3 is already a tuple with no brackets at all.
Example
a = (5)
b = (5,)
c = 5,
d = ()
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'tuple'>
print(c == b) # Output: True
print(len(d)) # Output: 0
def pair():
return 1, 2 # returns a tuple
x, y = pair()
print(x + y) # Output: 3This also explains print((1, 2)) versus print(1, 2): the first passes one tuple, the second passes two arguments.
What to say in the interview
"The comma, not the parentheses, creates a tuple. (5) is an int, while (5,) is a one-element tuple. Only the empty tuple needs just (). It matters for function arguments and for returning multiple values, which Python returns as a tuple."
Common mistakes
- Writing
("only",)without the comma and then looping over it, getting a string instead of a tuple of one item.