How to create a tuple with one item in Python
Overview
A tuple in Python is a collection of ordered and unchangeable items of the same data types stored in a single variable.
We can write tuples with round brackets ()
Creating a tuple
Let’s see how to create a tuple in the code below:
# creating a tuplemytuple = ("apple", "banana", "cherry")print("Tuple # 1: ", mytuple)print(type(mytuple), '\n')tuple2 = (511, "ID", 1.23, 'M')print("Tuple # 2: ", tuple2)
Note: The tuple
mytuplein the code above contains three items andtuple2contains four items of different types.
Creating tuple with a single item
As we can see from the previous code, mytuple contains three elements. Let’s rewrite the code and create the tuple with just a single element:
# creating a tuplemytuple = ("apple")print(mytuple)print(type(mytuple))
Explanation
The code above returns a string data type (<class 'str'>), not a tuple. We check the data type of the mytuple using the type() function.
The reason why our code does not return a tuple is that Python does not recognize the code mytuple = ("apple") as a tuple but rather as an str.
Solution
To create a tuple with only one item, we need to add a comma(,) after writing the item. Otherwise, Python will not recognize it as a tuple as seen in the previous code. Now let’s apply this logic:
# creating a tuple single item by adding a comma after the itemmytuple = ("apple",)print(mytuple)print(type(mytuple))
We can see from the output of the code (<class 'tuple'>) that we are able to create a tuple with a single item by adding a comma(,) right after the item.