Let’s see how to create one-element tuple in Python.
As you may know one-element tuple is not recognised as a tuple. Paranthesis is not making the element a tuple. For Python such element is a string.
my_tuple = ('Pythoneo') print(my_tuple) print(type(my_tuple))
Tuple comma trick
There is a trick to force Python to recognise one-element tuple as a tuple. It is enough to put a comma after such element.
my_tuple = ('Pythoneo',) print(my_tuple) print(type(my_tuple))
It may looks strange but actually it is working fine.
Tuple method
Another way to force Python to recognise one-element tuple as a actual tuple is to use a tuple method.
my_tuple = tuple(['Pythoneo']) print(my_tuple) print(type(my_tuple))
Please don’t forget using brackets! Without the brackets Python will create a tuple from separate letters.
my_tuple = tuple('Pythoneo') print(my_tuple) print(type(my_tuple))
Remark: For sure you noticed that for these tricks Python worked the same. No matter if you put comma at the end of one-element tuple or use tuple methon Python will put comma at the end of output tuple.