Count of an element in a tuple in python

Count Frequency of Element in a Tuple in Python

Tuples are ordered collection of items in Python. When working with tuples, it can be handy to know how to quickly an element’s frequency. In this tutorial, we will look at how to count the frequency of an element inside a tuple in Python with the help of examples.

Count of an element in a tuple in python

You can use the Python tuple count() function to count the frequency of an element in a tuple. Pass the element for which you want to count the occurrences as an argument to the function. The following is the syntax.

# frequency of item i in tuple t
t.count(i)

It returns the number of times the element appears in the tuple.

Let’s look at some examples of using the above syntax.

Let’s count the number of times a specific element occurs in a tuple.

# create a tuple
t = (7, 1, 3, 7, 7, 5, 1)
# frequency of 7 in t
print(t.count(7))

Output:

3

We get its frequency as 3. This is because the element 7 occurs three times in the tuple t.

Let’s look at another example.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s pass an element that is not present in the tuple as the argument to the count() function.

# create a tuple
t = (7, 1, 3, 7, 7, 5, 1)
# frequency of 7 in t
print(t.count(4))

Output:

0

We get 0 as the output. This is because the element 4 does not occur inside the tuple.

You can iterate over each distinct element in the tuple (use a set to get distinct tuple elements) and use the count() function to count its frequency in the tuple.

Let’s see an example.

# create a tuple
t = (7, 1, 3, 7, 7, 5, 1)
# distinct elements
unique_t = set(t)
# count of each element in tuple
for item in unique_t:
    print(f"Count of {item} in tuple t: {t.count(item)}")

Output:

Count of 1 in tuple t: 2
Count of 3 in tuple t: 1
Count of 5 in tuple t: 1
Count of 7 in tuple t: 3

Here we iterate through each unique element and then use the count() function to get its frequency in the tuple. We get the count of each element in the tuple as the output.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top