# Python program to count occurrences of an element in a tuple

We will see how to count occurrences of an element in a Tuple. A tuple is a sequence of immutable Python objects.

Let’s say we have the following input, with the occurrences of 20 to be checked −

myTuple = (10, 20, 30, 40, 20, 20, 70, 80)

The output should be −

Number of Occurrences of 20 = 3

Count occurrence of an element in a Tuple using for loop

In this example, we will count the occurrences of an element in a Tuple −

## Example

def countFunc(myTuple, a): count = 0 for ele in myTuple: if (ele == a): count = count + 1 return count # Create a Tuple myTuple = (10, 20, 30, 40, 20, 20, 70, 80) # Display the Tuple print("Tuple = ",myTuple) # The element whose occurrence is to be checked k = 20 print("Number of Occurrences of ",k," = ",countFunc(myTuple, k))

## Output

Tuple = (10, 20, 30, 40, 20, 20, 70, 80)
Number of Occurrences of 20 = 3

Count occurrence of an element in a Tuple using the count() method

In this example, we will count the occurrences of an element in a Tuple −

## Example

def countFunc(myTuple, a): return myTuple.count(a) # Create a Tuple myTuple = (10, 20, 30, 70, 20, 20, 70, 80) # Display the Tuple print("Tuple = ",myTuple) # The element whose occurrence is to be checked k = 70 print("Number of Occurrences of ",k," = ",countFunc(myTuple, k))

## Output

Tuple = (10, 20, 30, 70, 20, 20, 70, 80)
Number of Occurrences of 70 = 2

Updated on: 11-Aug-2022

633 Views