Python | Count occurrences of an element in a list

Created with Sketch.

Python | Count occurrences of an element in a list

Given a list in Python and a number x, count 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 
10 appears three times in given list.

Input : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
        x = 16
Output : 0

Method 1 (Simple approach)
We keep a counter that keeps on increasing if the esquired element is found in the list.

# 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 occured {} times'.format(x, countX(lst, x)))
Output:
8 has occured 5 times

Method 2 (Using count())
The idea is to use list method count() to count number of occurrences.

# 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 occured {} times'.format(x, countX(lst, x)))
Output:
8 has occured 5 times 

Method 2 (Using Counter())
Counter method returns a dictionary with occurences of all elements as a key-value pair, where key is the element and value is the number of times that element has occured.

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 occured {} times'.format(x, d[x]))
Output:
3 has occured 2 times

Leave a Reply

Your email address will not be published. Required fields are marked *