Tuple Methods in Python

Tuple Methods in Python

Tuple methods in Python are used on tuples to apply some operations on the elements the tuple is made up of. Before discussing various methods of tuple class and functions that can be called on a tuple object, we should know what a tuple is. A tuple is a collection of different types of data elements allowing you to store data of different type in one variable. It is immutable which means that once created, no new elements can be added into, no existing element can be deleted or value of no existing element of the tuple object can be changed.

 

Methods and Functions Description
count() It is a method and is used to return the number of occurrences of the specified element in the tuple object that calls it.
index() It is a method and is used to return the index of the first occurrence of the specified element in the tuple object that calls it.
len() It is a function and returns the number of elements the specified tuple object is made up of.
tuple() It is a function/constructor and is used to create a tuple object from the specified iterable object that can be a list, tuple, set, string, and dictionary, etc.

 

 

Tuple Methods in Python with Example

count() Method in Tuple Example

# Python program to illustrate count() method in tuple

Tuple = (10, 5, 50, 10, 50, 100)

n = Tuple.count(10)      
print(n)

In the program provided above, a tuple object with the name “Tuple” is created with 6 elements of same type which is int. count() method of tuple class is then called on the tuple object created above to count occurrences of 10 in it. Value returned is then displayed using print() built-in function to the console.

Output:

2

 

index() Method in Tuple Example

# Python program to illustrate index() method in tuple
Tuple = [1, 20, 3, 4, 5, 1, 7, 8]

#first occurrence of 1 in the whole tuple
pos = Tuple.index(1) 
print("The index of 1 is:", pos)

#first occurrence of 1 in the specified
#section of the tuple
y = Tuple.index(1, 1, 8) 
print("The index of 1 in index range [1,8) is:", y)

In the program provided above, a tuple object with the name “Tuple” is created with 8 elements of same type which is int. index() method of tuple class is then called on the tuple object created above to return the position of the first occurrence of 1 in it. Value returned is then displayed using print() built-in function to the console.

Output:

The index of 1 is: 0
The index of 1 in index range [1,8) is: 5

 

Share this post

Leave a Reply

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