In this post, we will explore different ways to count the occurrences of an item in a Python list.

1. Using list.count() function

One of the simplest method to get the occurrences of an item in a list is to use the list.count() function. This function is a built-in function of a list object that returns the number of times an item appears in a list.

Download  Run Code

2. Using operator.countOf() function

Another way to count the occurrences of an item in a Python list is to use the operator.countOf() function from the operator module. This function returns the number of occurrences of a value in an iterable. It is similar to the list.count() function but it can be used with other types of iterables as well.

Download  Run Code

3. Using collections.Counter() function

If we need the count of multiple items from the list, we can use the collections.Counter() function from the collections module. This function returns a dictionary-like object that contains counts of unique items in an iterable. The keys are the items and the values are their counts. We can then access the count for a specific item by passing the key to the get() function. Here is an example of how to use this function:

Download  Run Code

4. Using dictionary

Alternatively, we can create a frequency map using a dictionary to get the total number of occurrences of each item in a list. The following example demonstrates this by using the set() function to remove the duplicates and then use the count() function to get the frequency of each item:

Download  Run Code

 
However, this approach is not recommended for large lists. The time complexity of it is quadratic since the count() function is called once for each distinct element in the list. We can improve the performance by creating the frequency map manually, as shown below:

Download  Run Code

5. Using pandas.Series.value_counts() function

We can also use the pandas.Series.value_counts() function to count the occurrences of an item in a list. This function returns a Series object that contains the counts of each unique value in the original list. Here is a simple example of its usage:

Download Code

That’s all about counting occurrences of an item in a list in Python.