How to count the occurrences of the element or item in a Python list? To count the occurrences of an element in a list in Python, you can use the list.count()
method. This method returns the number of times the element appears in the list. And you can also use the Counter
class from the collections
module to count the occurrences of elements in a list. The Counter
class is a dictionary subclass that is specifically designed for counting occurrences of elements.
In this article, I will explain the list.count()
, Counter
, and other ways to get the count of occurrences of a single value and all values in a list.
1. Quick Examples of Count Occurrence of Item in List
If you are in a hurry, below are some quick examples of how to count the occurrence of an element or item in a Python list.
# Quick examples of count occurrence list
# Example 1: Count occurrences using count()
count = list2.count(67)
# Example 2: Count occurrences using Counter
from collections import Counter
count = Counter(list2)[67]
# Example 3: Using operator
import operator
count = operator.countOf(list2,'AA')
# Example 4: Using list comprehension
count = len([i for i in list2 if i==12])
# Example 5: Get count occurrence of all values
from collections import Counter
count = Counter(list2)
# Example 6: Get all occurrences using pandas
pd.Series(list2).value_counts()
2. Count of Item Occurrence in List using count()
The count()
is an inbuilt function available in Python list that is used to get the count of occurrence of an item/element. This function takes a single item as an argument and returns the total occurrence of an item present in the list. If the item is not found, 0 is returned.
2.1 count() Syntax
Following is the syntax of the count()
# Syntax
list2.count(element)
list
: The list in which you want to count occurrences.element
: The element whose occurrences you want to count.
2.2 Occurance Count Example
Let’s create a list with several integer values, some with duplicates, and use the count()
function to find the count of a specific value.
# Create list of elements
list2=[12,54,67,86,89,12,54,67,67,67,66]
print("Original list:\n", list2)
# Count occurrences using count()
print("67 occurrence: ",list2.count(67))
print("86 occurrence: ",list2.count(86))
print("99 occurrence: ",list2.count(99))
Yields below output.
From the output,
- 67 occurred 4 times
- 86 occurred 1 times
- 99 occurred 0 times
Similarly, you can also find the number of occurrences on the list with string values.
3. Count of Item Occurrence in List using Counter()
You can also get the count of occurrences of elements from the list by using the Counter()
method from the Python collections
module, In order to use the Counter first, we need to import the Counter from the collections module. The Counter
class is a dictionary subclass that is specifically designed for counting occurrences of elements.
3.1 Counter() Syntax
Following is the syntax of the counter usage.
# Syntax of Counter
from collections import Counter
Counter(list2)[element]
3.2 Counter Example
The Counter() takes the list as an argument and returns the occurrence count of every element in the list as a Counter class. To get a count for a specific element you need to specify the value using []
. Here’s an example:
# Import Counter from collections
from collections import Counter
# Count occurrences using Counter
print("67 occurrence: ",Counter(list2)[67])
print("86 occurrence: ",Counter(list2)[86])
print("99 occurrence: ",Counter(list2)[99])
# Output:
# 67 occurrence: 4
# 86 occurrence: 1
# 99 occurrence: 0
4. Using countOf()
The countOf()
is similar to the count() function which is available in the operator module. You need to import the operator module to use this.
4.1 countOf() Syntax
Following is the syntax of the countOf().
# Syntax of countOf()
import operator
operator.countOf(list2,element)
4.2 countOf() Example
Here, let’s create a list with strings and use the countOf() to get the count of occurrence of the item.
# Import operator
import operator
# Create List with string
list2=['AA','AB','AA','BB','AA','CC']
# Get Occurrences of item
print("AA occurrence: ",operator.countOf(list2,'AA'))
print("CC occurrence: ",operator.countOf(list2,'CC'))
print("DD occurrence: ",operator.countOf(list2,'DD'))
# Output
# AA occurrence: 3
# CC occurrence: 1
# DD occurrence: 0
5. Using List Comprehension
Like the above scenario, we will use for loop inside the List comprehension to iterate all elements and use if condition to check the condition. So by using the len() function, we will get the total occurrence of element.
5.1 List Comprehension Syntax
Following is the syntax.
# Here, element is the item, in which all occurrences is counted in list2.
# iterator is used to iterate the elements in our input list.
len([iterator for iterator in list2 if iterator == element])
5.2 Example
Let’s get the total occurrences of element 12.
# Consider list of elements
list2=[12,54,67,86,89,12,54,67,67,67,67]
print("Elements: ",list2)
# Using List Comprehension
print("12 occurrence: ",len([i for i in list2 if i==12]))
# Output:
# Elements: [12, 54, 67, 86, 89, 12, 54, 67, 67, 67, 67]
# 12 occurrence: 2
6. Using for loop
In this scenario, we will iterate each element using for loop and compare if the iterator is equal to an element or not inside the if condition. If the iterator is equal to our item/element, we will increment the counter(inc) to 1. The result the stored inside the inc variable.
Let’s get the total occurrences of element 67 using for loop.
# Consider list of elements
list2=[12,54,67,86,89,12,54,67,67,67,67]
print("Elements: ",list2)
# Using for loop to count
# occurrence if 67
inc=0
for i in list2:
if (i == 67):
inc = inc + 1
print("67 occurrence: ",inc)
# Output:
# Elements: [12, 54, 67, 86, 89, 12, 54, 67, 67, 67, 67]
# 67 occurrence: 5
7. Using value_counts()
Till now, we discussed how to count the total occurrences of a particular item in the list. Now, we will see how to return the total occurrences of all elements from the list using value_counts()
method from the pandas module.
Python pandas is a module that is used for Data analysis and visualization. Series is one of the Data structures supported by pandas. It is a one-dimensional data structure. We can apply the value_counts() method on this Series Data structure. To do so, first, you need to convert the list to a series.
7.1 value_counts() Syntax
Following is the syntax of the value_counts()
# Syntax
import pandas as p
p.Series(list2).value_counts()
7.2 Example
Let’s get the count of all element occurrences.
# Import pandas
import pandas as pd
# Consider list of elements
list2=["hello","hello","java"]
print("Elements: ",list2)
# Using value_counts() to return all element occurrences
pd.Series(list2).value_counts()
# Output:
# Elements: ['hello', 'hello', 'java']
# hello 2
# java 1
# dtype: int64
Frequently Asked Questions On Python Count Occurrence List
To count the occurrences of a specific element in a list in Python, you can use the count
method of the list. For example, my_list.count(1)
will return the number of occurrences of the element 1
in the list my_list
.
You can use a dictionary comprehension with the count
method or utilize collections.Counter
.
You can use numpy
to count occurrences in a list. For example, np.unique(my_list, return_counts=True)
returns two arrays: unique_elements
contains the unique elements in my_list
, and counts
contains the corresponding counts. The zip
function is then used to combine these two arrays into a dictionary, where the unique elements are the keys, and the counts are the values.
You can use pandas
to count occurrences. For example, pd.Series(my_list)
converts the list into a pandas Series, and value_counts()
is then applied to get the counts of unique elements. Finally, to_dict()
is used to convert the result into a dictionary.
You can calculate percentages by dividing the count of each element by the total count.
Conclusion
In this article, we have seen 6 different ways to count the total occurrences of a particular item in the Python list. If you want to know all the element occurrences, then use the value_counts()
method available in the Pandas Series.
Happy Learning!!