Open In App

Python | Count occurrences of an element in a list

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list in Python and a number x, count the number of occurrences of x in the given list.

Examples: 

Input: lst = [15, 6, 7, 10, 12, 20, 10, 28, 10], x = 10
Output: 3 
Explanation: 10 appears three times in given list.
Input: lst = [8, 6, 8, 10, 8, 20, 10, 8, 8], x = 16
Output: 0
Explanation: 16 appears zero times in given list.

Count Occurrences of Item in Python List

Below are the methods by which we can count all occurrences of an element in a Python List.

Python Count occurrences using a Loop in Python

We keep a counter that keeps on increasing if the required element is found in the list.

Python3




# Python code to count the number of occurrences
def countX(lst, x):
    count = 0
    for ele in lst:
        if (ele == x):
            count = count + 1
    return count
 
 
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x,
                                        countX(lst, x)))


Output

8 has occurred 5 times

Python Count Occurences using List Comprehension

In this example, we are using list comprehension to count all occurrences of an element in a Python list.

Python3




l = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]
ele=1
x=[i for i in l if i==ele]
print("the element",ele,"occurs",len(x),"times")


Output

the element 1 occurs 2 times

Python Count using Enumerate Function

In this example, we are using enumerate function to count all occurrences of an element in a Python list.

Python3




l = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]
ele=1
x=[i for j,i in enumerate(l) if i==ele]
print("the element",ele,"occurs",len(x),"times")


Output

the element 1 occurs 2 times

Count occurrences of an element using count()

The idea is to use the list method count() to count the number of occurrences. 

Python3




# Python code to count the number of occurrences
def countX(lst, x):
    return lst.count(x)
 
 
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x,
                                        countX(lst, x)))


Output

8 has occurred 5 times

Python Count occurrences of an element in a list using Counter()

The counter method returns a dictionary with occurrences of all elements as a key-value pair, where the key is the element and the value is the number of times that element has occurred. 

Python3




from collections import Counter
 
# declaring the list
l = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
 
# driver program
x = 3
d = Counter(l)
print('{} has occurred {} times'.format(x, d[x]))


Output

3 has occurred 2 times

Count occurrences of an element using countOf()

Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.

Python3




import operator as op
 
# declaring the list
l = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]
 
# driver program
x = 2
print(f"{x} has occurred {op.countOf(l, x)} times")


Output

2 has occurred 3 times

Using Python Dictionary Comprehension

Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}

Python3




lis = ['a', 'd', 'd', 'c', 'a', 'b', 'b', 'a', 'c', 'd', 'e']
occurrence = {item: lis.count(item) for item in lis}
print(occurrence.get('e'))


Output

1

Using the Pandas library

Pandas Series.value_counts() function return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element.

Python3




import pandas as pd
 
# declaring the list
l = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]
 
count = pd.Series(l).value_counts()
print("Element Count")
print(count)


Output:

Element    Count
2            3
1            2
3            2
4            2
5            2
dtype: int64


Similar Reads

Python | Count occurrences of an element in a Tuple
In this program, we need to accept a tuple and then find the number of times an item is present in the tuple. This can be done in various ways, but in this article, we will see how this can be done using a simple approach and how inbuilt functions can be used to solve this problem. Examples: Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)Input : 4
3 min read
Python - Get the indices of all occurrences of an element in a list
In this article, we will be going to understand how to get all the indices of an element in a list in Python and we will also cover a few of the best approaches to do so. Example Input: my_list = [1, 2, 3, 1, 5, 4] item = 1Output: 0,3Explanation: The output contains all the index of element 1 in the my_list.Find List Index of All Occurrences of an
5 min read
Remove all the occurrences of an element from a list in Python
The task is to perform the operation of removing all the occurrences of a given item/element present in a list. Example Input1: 1 1 2 3 4 5 1 2 1 Output1: 2 3 4 5 2 Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1. After removing the item, the output list is [2, 3, 4, 5, 2]Remove all Occurrences of an Item fr
4 min read
Python | Count String occurrences in mixed list
Sometimes, while working with data, we can have a problem in which we need to check for the occurrences of a particular data type. In this, we can also have a problem in which we need to check for string occurrences. Let's discuss certain ways in which this task can be performed. Method #1 : Using isinstance() + list comprehension The combination o
8 min read
Python | Count occurrences of a character in string
Given a string, the task is to count the frequency of a single character in that string using Python. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters. Example Input:'GeeksForGeeks'Output:'4'Explanation: In this, we have counted the occurrence of 'e' in the string.
6 min read
Python - Count occurrences of each word in given text file
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the word is already present in the dictionary we increm
4 min read
Python program to Count the Number of occurrences of a key-value pair in a text file
Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with Python Program to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular expressions (re module)Text file: Naive Approach to
3 min read
Python | Remove all occurrences in nested list
The task of removing an element generally doesn't pose any challenge, but sometimes, we may have a more complex problem than just removing a single element or performing removal in just a normal list. The problem can be removing all occurrences of the nested list. Let's discuss certain ways in which this problem can be solved. Method #1: Using list
5 min read
Python - All occurrences of Substring from the list of strings
Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is recommended for CS'] Explanation : Result strings have
5 min read
Python program to Occurrences of i before first j in list
Given a list, the task is to write a Python program to count the occurrences of ith element before the first occurrence of jth element. Examples: Input : test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9], i, j = 4, 8 Output : 3 Explanation : 4 occurs 3 times before 8 occurs. Input : test_list = [4, 5, 6, 4, 1, 4, 8, 5, 4, 3, 4, 9], i, j = 5, 8 Outpu
6 min read
Practice Tags :