How to create a tuple in Python | Basics

To create a tuple use parenthesis ( ) in Python. To assign value place all the elements in a () parenthesis, separated by commas.

my_tuple = ()

Tuple elements are ordered, unchangeable, and allow duplicate values. A tuple can have any number of elements and they may be of different types (Number, float, list, string, etc.).

How to create a tuple in Python example

Simple example code of Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed data types
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("King", [0, 0, 0], (1, 2, 3))
print(my_tuple)

Output: Tuples are written with round brackets.

How to create a tuple in Python

Another example create a tuple without using parentheses

my_tuple = 3, 4.6, "A"

print(my_tuple)
print(type(my_tuple))

Output: (3, 4.6, ‘A’)

How to create a tuple with only one element?

Answer: Use a trailing comma to indicate that a tuple with a single element.

my_tuple = ("Hello",)

print(type(my_tuple))
Output: <class 'tuple'>

Do comment if you have any doubts and suggestions on this python tuple basic topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.