Python Tuple Methods

In Python, Tuple methods are built-in functions that we can use to perform different operations on tuples. These methods provides a convenient way for manipulating and analyzing tuple data.

Since tuple is an immutable collection of elements, there are only a few built-in methods available for us to work with. Unlike lists, we cannot add, remove, or sort elements in a tuple once it’s created.

The only two built-in methods that tuples support are:

  1. count()
  2. index()

We are now going to discuss these methods with the help of examples:

Tuple count() Method

The count() method is a built-in Python method that allow us to count the occurrence of the specified element in a tuple. This method takes a single argument as the element to be counted and returns its occurrence in the given tuple.

Python Tuple Methods

Syntax:

The syntax of the count() method is shown below:

tuple_name.count(item)  

Parameter:

  • item (required):The item parameter is the element to be searched in the tuple.

Return:

  • The number of times the specified item appeared in the tuple.

Python Tuple count() Method Example

We are now going to look at a simple example showing the use of the tuple’s count() method in Python.

Example

# simple python program to show the use of the count() method  

  

# given tuples  

tuple_of_numbers = (1, 3, 4, 5, 2, 4, 6)  

tuple_of_countries = ('Pakistan', 'USA', 'France', 'USA',   

                      'Germany', 'Pakistan', 'Pakistan', 'Brazil', 'Japan')  

  

print("Tuple 1:", tuple_of_numbers)  

# counting the occurrence of 4  

count_of_4 = tuple_of_numbers.count(4)  

print("Count of 4:", count_of_4)  

  

print() # empty line  

print("Tuple 2:", tuple_of_countries)  

# counting the occurrence of 'Pakistan'  

Pakistan = tuple_of_countries.count('Pakistan')  

print("Count of Pakistan:", Pakistan)

Output:

Tuple 1: (1, 3, 4, 5, 2, 4, 6)
Count of 4: 2

Tuple 2: ('Pakistan', 'USA', 'France', 'USA', 'Germany', 'Pakistan', 'Pakistan', 'Brazil', 'Japan')
Count of Pakistan: 3

Explanation:

Here, we have used the count() method to find the total occurrences of the specified elements in the given tuples.

Python Example to count nested tuples and lists in Tuples

Let us now see another example showing the way of counting nested tuples and lists in Tuples.

Example

# python example to count nested tuples and lists  

  

# given tuple  

given_tuple = ((4, 5), 1, (4, 5), [4, 5], (2, ), 4, 5)  

print("Given Tuple:", given_tuple)  

  

# counting the tuple (4, 5) in given tuple  

tpl_1 = given_tuple.count((4, 5))  

print("Count of (4, 5):", tpl_1)  

  

# counting the list [4, 5] in given tuple  

lst_1 = given_tuple.count([4, 5])  

print("Count of [4, 5]:", lst_1)

Output:

Given Tuple: ((4, 5), 1, (4, 5), [4, 5], (2,), 4, 5)
Count of (4, 5): 2
Count of [4, 5]: 1

Explanation:

Here, we have used the count() method to find the total occurrence of the specified tuple and list in the given tuple.

Tuple index() Method

The index() method is a built-in Python method allows us to search for a specified element in the tuple and return its position. We can also select an optional range in order to search a particular region in the tuple.

Python Tuple Methods

Syntax:

The syntax of the index() method is shown below:

tuple_name.index(item[, start[, stop]])  

Parameter:

  • item (required): The item parameter is the element to be searched in the tuple.
  • start (optional): The start parameter specifies the starting index for the search.
  • end (optional): The end parameter specifies the ending index.

Return:

  • An Integer Value indicating the index of the first occurrence of the specified value.

Note: This method is raise a ValueError exception if the specified element is not found in the tuple.

Python Tuple index() method Example

We are now going to see a simple example to understand the working of the tuple’s index() method in Python.

Example

# simple python program to show the use of the index() method  

  

# given tuple  

tuple_of_fruits = ('orange', 'apple', 'banana', 'mango',   

                   'apple', 'melon', 'cherries', 'grapes')  

print("Given Tuple:", tuple_of_fruits)  

  

# getting the index of 'apple'  

idx_of_apple = tuple_of_fruits.index('apple')  

print("First occurrence of 'apple':", idx_of_apple)  

  

# getting the index of 'apple' after 3rd index  

idx_of_apple = tuple_of_fruits.index('apple', 3)  

print("First occurrence of 'apple' after 3rd index:", idx_of_apple)

Output:

Given Tuple: ('orange', 'apple', 'banana', 'mango', 'apple', 'melon', 'cherries', 'grapes')
First occurrence of 'apple': 1
First occurrence of 'apple' after 3rd index: 4

Explanation:

Here, we have used the index() method to find the first appearance of the specified elements in the given tuple.

Python Tuple index() Method Example Without Any Element

Let us see an example showing what will happen if the element does not exist in the given tuple.

Example

# example to find element that is not found in the tuple  

  

# given tuple  

tpl_1 = (1, 3, 4, 5, 6, 2, 7, 4, 9, 1)  

  

# getting the index of 8  

idx_of_8 = tpl_1.index(8)

Output:

ValueError: tuple.index(x): x not in tuple

Explanation:

Here, we can observe that the index() method has raised the ValueError exception as the specified element is not found in the given tuple.

Python Tuple Methods FAQs

1. Do tuples have methods in Python?

Yes, Python tuples have two built-in methods:

  • count(): This method is used to return the number of times the specified element appears in the tuple.
  • index(): This method is used to return the first index of the specified element in the tuple. It raises a ValueError exception if the element is not found.

2. Why are there only a few methods available for tuples?

Tuple is an immutable data type, meaning we cannot change its content once created. Most list methods, like append() or remove(), modify data, so they are not available for tuples.

3. Can we add or remove items from a tuple?

No, we cannot directly add or remove elements from a tuple because it is immutable. However, we can create a new tuple by combining the existing ones, as shown in the following example:

Example

# given tuple  

tpl_1 = (1, 3, 5, 2)  

  

# creating a new tuple  

tpl_2 = tpl_1 + (4,)  

print(tpl_2)

Output:

(1, 3, 5, 2, 4)

4. How to convert a tuple to a list to modify it?

We can make use of the list() function to convert a given tuple to a list, make changes, and then convert it back.

Here is an example showing the way of converting a tuple to a list:

Example

# given tuple  

tpl_1 = (1, 3, 5, 2)  

  

# converting tuple to a list  

lst_1 = list(tpl_1)  

lst_1.append(4) # making changes  

  

# converting list back to a tuple  

tpl_1 = tuple(lst_1)  

print(tpl_1)

Output:

(1, 3, 5, 2, 4)

5. Can we store mutable elements like lists inside a tuple?

Yes, but we need to be cautious while storing mutable elements like lists inside a tuple. The tuple itself remains immutable; however, we can change the mutable elements like the list inside it.

Let us see an example:

Example

# given tuple  

tpl_1 = ([1, 3], 5)  

  

# changing list inside the tuple  

tpl_1[0].append(2)  

print(tpl_1)

Output:

([1, 3, 2], 5)

Comments

Leave a Reply

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