In Python, tuple with a single item has a specific syntax requirement to avoid confusion with parentheses used for grouping expressions.
Using a Trailing Comma
The most common way to create a single-item tuple is by placing a trailing comma. This tells Python that given expression is a tuple.
# Correct way to define a single-item tuple
t = (5,)
print(t)
print(type(t))
Output
(5,) <class 'tuple'>
Common Mistake: Missing the Trailing Comma
If we miss the trailing comma, Python treats the parentheses as grouping for an expression instead of defining a tuple.
# Incorrect - This is an integer, not a tuple
t = (5)
print(t)
print(type(t))
Output
5 <class 'int'>
Using the tuple() Constructor
Using tuple constructor works only for iterable items (like string, list etc).
# Using tuple() with a single-item list
t = tuple([5])
print(t)
print(type(t))
# using a string iterable inside tuple() constructor
t = tuple("A")
print(t)
print(type(t))
# Below code would not work as integer is not iterable
# t = tuple(5)
Output
(5,)
<class 'tuple'>
('A',)
<class 'tuple'>