
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Occurrences of an Element in a Tuple in Python
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
Advertisements