Python Datatypes

Python Tuple (With Examples)

You may want to construct a list of objects that cannot be altered while the application is running. Python Tuples are utilized to meet this requirement. They are frequently utilized internally in many of the systems on which we rely, such as databases. In Python, tuples are a fundamental data structure. Tuples store data in the sequence in which we input it. In this tutorial, we will look at the Python tuple and its numerous methods, uses, and so on.

Python Tuple

Python Tuple is an immutable (unchangeable) collection of various data type elements. Tuples are used to keep a list of immutable Python objects. The tuple is similar to lists in that the value of the items placed in the list can be modified, however the tuple is immutable and its value cannot be changed.

Creating a Tuple

A tuple is formed by enclosing all of the items (elements) in parentheses () rather than square brackets [], and each element is separated by commas. A tuple can contain any number of objects of various sorts (integer, float, list, string, etc.). A tuple can include elements with different data types. You can also specify nested tuples, which have one or more entries that are lists, tuples, or dictionaries.

Example

                    

# Python program to create Tuples
# empty tuple
my_tuple = ()
print(my_tuple)

# tuple with integer values
num = (100, 35, 7, 21)
print(num)

# tuple with mixed values
my_tuple = (23.545, 'Hello', 'A', 785)
print(my_tuple)

# nested tuples
my_tuple = ('Python', [2, 4, 6], (1, 3, 5))
print(my_tuple)

Output

                    

()
(100, 35, 7, 21)
(23.545, 'Hello', 'A', 785)
('Python', [2, 4, 6], (1, 3, 5))

A tuple can also be formed without the use of parentheses. This is referred to as Tuple Packing. The parentheses are optional, however, it is recommended that they be used.

Example

                    

# Python program to create Tuples
val = 100, 00.245, 'Apple', 21
print(val)
 
# tuple unpacking is also possible
a, b, c, d = val
print(a)
print(b)
print(c)
print(d)

Output

                    

(100, 0.245, 'Apple', 21)
100
0.245
Apple
21

Creating a tuple using only 1 value element is a bit tricky. To create a tuple containing only 1 element, we need to succeed it by a trailing comma to indicate that it is a tuple.

Example

                    

# Python program to create Tuples
my_tuple = ('Programming')
print(type(my_tuple))

# Creating a tuple having one element
my_tuple = ('Programming',)
print(type(my_tuple))

# Parentheses is optional
my_tuple = 'Python',
print(type(my_tuple))

Output

                    

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Access Tuple Elements

Each item in a tuple has its own index value, which starts at zero. Index values are incremented by one. An individual item in a tuple can be accessed by referencing the item’s index value. Indexes are integers that range from 0 to n-1, where n is the number of entries. The elements of a tuple can be accessed in a variety of ways.

  • Indexing Method

To retrieve an item in a tuple, we can use the index operator [], where the index starts at 0. As a result, a tuple with 5 items will have indices ranging from 0 to 4. Attempting to access an index that is not inside the tuple index range will result in an IndexError. We can’t use floats or other types because the index must be an integer. This will produce a TypeError.

Example

                    

# Python program to access tuple elements
my_tuple = ('I', 'Love', 'To', 'Code', 'In', 'Python')
print('Tuple:', my_tuple)

print('Element at index 1:', my_tuple[1])
print('Element at index 5:', my_tuple[5])

# IndexError: list index out of range
# print(my_tuple[10])

# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[5.0]

Output

                    

Tuple: ('I', 'Love', 'To', 'Code', 'In', 'Python')
Element at index 1: Love
Element at index 5: Python

  • Negative Indexing Method

Python sequences support negative indexing. The value of -1 denotes the last item, the index of -2 the second last item, and so on.

                    

# Python program to access tuple elements
my_tuple = ('I', 'Love', 'To', 'Code', 'In', 'Python')
print('Tuple:', my_tuple)

print('Element at index -1:', my_tuple[-1])
print('Element at index -5:', my_tuple[-3])

Output

                    

Tuple: ('I', 'Love', 'To', 'Code', 'In', 'Python')
Element at index -1: Python
Element at index -5: Code

  • Slicing

If we wish to obtain a range of items from our tuple, we may give a range of indexes. This is known as the Slicing method. You can slice a tuple and other sequential data types in Python using the following syntax:

                    

tuple_name[start: stop: step]

Example

                    

# Python program to access tuple elements using slicing
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')

# elements from 1st index to 5th index
print(my_tuple[1:6])

# from 5th element till end
print(my_tuple[5:])

# till 3rd element
print(my_tuple[:4])

# entire set
print(my_tuple[:])

Output

                    

('r', 'o', 'g', 'r', 'a')
('a', 'm', 'm', 'i', 'n', 'g')
('p', 'r', 'o', 'g')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')

Changing a Tuple

Tuples, unlike lists, are immutable. This means that once a tuple’s elements have been allocated, they cannot be modified. However, if the element is a changeable data type, such as a list, its nested components can be altered. If you attempt to alter a tuple element, you will receive a TypeError error.

                    

# Python program to change tuple elements
my_tuple = (10, 20, 35, 40, 50)

my_tuple[2] = 30
print(my_tuple)

Output

                    

Traceback (most recent call last):
  File "", line 4, in 
TypeError: 'tuple' object does not support item assignment

However, entire tuple can be reassigned new values. For example,

                    

# Python program to change tuple elements
my_tuple = (10, 20, 35, 40, 50)
print('Original Tuple:', my_tuple)

# entire tuple can be reassigned a new value
my_tuple = ('A', 'B', 'C', 'D')
print('New Tuple:', my_tuple)

Output

                    

Original Tuple: (10, 20, 35, 40, 50)
New Tuple: ('A', 'B', 'C', 'D')

Deleting a Tuple

As previously stated, because tuples are immutable, we cannot delete elements from them. We cannot delete or remove entries from a tuple as a result. However, the verb del can be used to completely delete a tuple.

Example

                    

# Python program to delete entire tuple
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')

# deletes entire tuple
del my_tuple
print(my_tuple)

Output

                    

Traceback (most recent call last):
  File "", line 6, in 
NameError: name 'my_tuple' is not defined

Tuple Methods

Tuples only supports the following two methods:

                    

# Python program to delete entire tuple
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')
print(my_tuple)

print('Count of letter g:', my_tuple.count('g'))
print('Index of letter a:', my_tuple.index('a'))

Output

                    

('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')
Count of letter g: 2
Index of letter a: 5

Built-in Python Tuple Functions

Function Description
cmp(tuple1, tuple2) Compares elements of both the tuples
len(tuple) Returns the total length of the tuple
max(tuple) Returns the largest element from the tuple
min(tuple) Returns the smallest element from the tuple
tuple(seq) Converts a list into tuple

Example

                    

tup1 = ('A', 'E', 'G', 'B')
tup2 = ('A', 'Z', 'E', 'L')

if(cmp(tup1, tup2) != 0):
    print('Tuples are not same')
else:
    print('Tuples are same')

print('Max value in tup1 is:', max(tup1))
print('Min value in tup2 is:', min(tup2))

Output

                    

Tuples are not same
Max value in tup1 is: G
Min value in tup2 is: A

Other Tuple Operations

  • Tuple Membership Test

Using the in and not in keyword, we can determine whether or not an item exists in a tuple.

                    

my_tuple = ('p', 'y', 't', 'h', 'o', 'n')

# In operation
print('a' in my_tuple)
print('p' in my_tuple)

# Not in operation
print('q' not in my_tuple)

Output

                    

False
True
True

  • Iterating through a Tuple

To iterate through each element of the Python tuple, we use for loop.

                    

names = ('John', 'Tina', 'Kim')

for i in names:
    print('Hello', i)

Output

                    

Hello John
Hello Tina
Hello Kim

Advantages of Tuple over List

Tuples and lists are utilized in similar situations because they are so similar. However, there are some advantages to using a tuple instead of a list.

  • The Tuples, unlike lists, cannot be updated. A tuple cannot be added, removed, or replaced.
  • Tuples are typically used for heterogeneous (different) data types, while lists are typically used for homogeneous (similar) data types.
  • Because tuples are immutable, iterating through them is faster than iterating through a list. As a result, there is a modest performance boost.
  • Tuples with immutable elements can be used as a dictionary key. This is not feasible with lists.
  • If you have non-changing data, implementing it as a tuple ensures that it remains write-protected.
  • If you want to change the data of a tuple, we need to convert it first into a list.

Frequently Asked Questions

Q1. What is a tuple in Python?

Python Tuple is an immutable (unchangeable) collection of various data type elements. Tuples are used to keep a list of immutable Python objects. The tuple is similar to lists in that the value of the items placed in the list can be modified, however, the tuple is immutable and its value cannot be changed.

Q2. How do you initialize a tuple in Python?

A tuple is formed by enclosing all of the items (elements) in parentheses () rather than square brackets [], and each element is separated by commas. A tuple can contain any number of objects of various sorts (integer, float, list, string, etc.). A tuple can include elements with different data types. You can also specify nested tuples, which have one or more entries that are lists, tuples, or dictionaries.

Example

                    

# Python program to create Tuples
# tuple with integer values
num = (100, 35, 7, 21)
print(num)

# tuple with mixed values
my_tuple = (23.545, 'Hello', 'A', 785)
print(my_tuple)

# nested tuples
my_tuple = ('Python', [2, 4, 6], (1, 3, 5))
print(my_tuple)

Output

                    

(100, 35, 7, 21)
(23.545, 'Hello', 'A', 785)
('Python', [2, 4, 6], (1, 3, 5))

A tuple can also be formed without the use of parentheses. This is referred to as Tuple Packing. The parentheses are optional, however, it is recommended that they be used.

Example

                    

# Python program to create Tuples
val = 100, 00.245, 'Apple', 21
print(val)

Output

                    

(100, 0.245, 'Apple', 21)

Q3. How does Python recognize a tuple?

The basic way to identify a tuple in Python is to check if the variables/elements are inside rounded brackets/parentheses. Other methods include:

  • Using type() – It checks the type of variable and can also be used to check tuples.
  • Using isinstance() – To determine whether obj is a tuple, we can use isinstance(var, class), where var is the variable to compare and class is a tuple.

Example

                    

fruits = ('Apple', 'Banana', 'Peach', 'Kiwi')
vehicles = 'Car', 'Bus', 'Bike'

print(type(fruits))
print(type(vehicles))

print(isinstance(fruits, tuple))
print(isinstance(vehicles, tuple))

Output

                    

<class 'tuple'>
<class 'tuple'>
True
True

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.