Skip to content

How to create a tuple in Python | Basics

  • by

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 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 is creating 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 a tuple with a single element.

my_tuple = ("Hello",)

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

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading