What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Count Occurrences of Element in Python List

  • Dec 06, 2021
  • 5 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Shivali Bhadaniya
Count Occurrences of Element in Python List

Python is well known for its easy syntax, fast implementation, and, most importantly, large support of multiple data structures. Lists are one of those data structures in python which helps to store large amounts of sequential data in a single variable. As huge data is stored under the same variable, it is sometimes quite difficult to manually identify whether the given element is present in the lists, and if yes, how many times. Therefore, in this article, we will study the various ways to count the number of occurrences in the list in python. To recall the concepts of python lists in detail, visit our article “3 Ways to Convert List to Tuple”. 

How to Count the Number of Occurrences in the List?

There are six ways by which you can count the number of occurrences of the element in the list. Let us study them all in brief below:

1) Using count() method

count() is the in-built function by which python count occurrences in list. It is the easiest among all other methods used to count the occurrence. Count() methods take one argument, i.e., the element for which the number of occurrences is to be counted.

For example:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
print(sample_list.count("a"))
print(sample_list.count("ab"))

 

Output

2
3

 

2) Using a loop

Another simple approach to counting the occurrence is by using a loop with the counter variable. Here, the counter variable keeps increasing its value by one each time after traversing through the given element. At last, the value of the counter variable displays the number of occurrences of the element.

For example:

def countElement(sample_list, element):
	return sample_list.count(element)


sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
element = "ab"
print('{} has occurred {} times'.format(element, countElement(sample_list, element)))

 

Output

ab has occurred 3 times

 

3) Using countof() method

Operator module from python library consists of countof() method which helps to return the number of occurrence of the element from the lists. This method takes two arguments, i.e., the list in which the count needs to be performed and the element which needs to be found. Moreover, you have to import the operator module before beginning the program using the “import” keyword as shown below:

For example:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

import operator as op

print(op.countOf(sample_list,"a"))

 

Output

2

 

4) Using counter() method

Python possesses an in-built module named collections, including multiple methods to ease your programming. One such method is a counter() method where elements are stored as a dictionary with keys and counts as values.

Therefore, the counter() method helps you return the total number of occurrences of a given element inside the given list by taking one parameter as the list in which the element is to be counted. Remember that you have to import the collections module to use the counter() method as shown in the below example:

For example:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

from collections import Counter

print(Counter(sample_list))

c = Counter(sample_list) 
print(c["a"])

 

Output

Counter({'ab': 3, 'a': 2, 'abc': 1})
2

 

5) Using pandas library

Pandas is the in-built python library, highly popular for data analysis and data manipulation. It is an open-source tool with a large range of features and is widely used in the domains like machine learning and artificial intelligence. To learn more about pandas, please visit our article “Numpy vs Pandas.”

Pandas possess a wide range of default methods, one of which is the value_count() method. Along with the value_count() method, pandas use series, i.e., a one-dimensional array with axis label.

To count the occurrence of elements using pandas, you have to convert the given list into the series and then use the value_count() method, which returns the object in descending order. By these, you can easily note that the first element is always the most frequently occurring element.

Check out the below example for a better understanding of the Pandas library

For example:

import pandas as pd

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
count = pd.Series(sample_list).value_counts()
print(count["a"])

Output

2

 

6) Using loops and dict in python

This is the most traditional method by which python count occurrences in the list that is by using the loop, conditional statement, and dictionaries. By this method, you have to create the empty dictionary and then iterate over the list. Later, check if the element present in the list is available in the dictionary or not. If yes, then increase its value by one; otherwise, introduce a new element in the dictionary and assign 1 to it. Repeat the same process until all the elements in the lists are visited.

Remember that this method is quite different from the previous method using the loop and the counter variable. The early mentioned method does not make use of dictionary data structure, whereas this one does. At last, print the count of occurrence of each element as shown in the below example:

For example:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

def countOccurrence(a):
  k = {}
  for j in a:
    if j in k:
      k[j] +=1
    else:
      k[j] =1
  return k

print(countOccurrence(sample_list))

 

Output

{'a': 2, 'ab': 3, 'abc': 1}

 

Conclusion

Programming is all about reducing manual tasks and shifting to automation. Counting the occurrence of elements from the large dataset manually is quite a tedious and time-consuming task. Therefore, python provides various methods by which you can count the occurrence of elements easily and quickly with few lines of code, just like shown in the article above. It is recommended to learn and understand all these methods to make your programming effective and efficient.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.