Count occurrences of an element in list

Learn 3 ways to count occurrences of an element in a list in Python.

Count occurrences of an element in list

In this article, we will discuss 3 different ways of counting occurrences of an element in a python list. The below output is what we want to achieve.

my_list = [2, 3, 5, 3, 6, 3, 7, 3]
num = 3 # element to count
count ==> 4

Method 1 - Using for loops

The below method uses for loops and f-strings in Python.

def get_count(lst, num):
    my_count = 0
    for elem in lst:
        if (elem == num):
            my_count = my_count + 1
    return my_count
 
my_list = [2, 3, 5, 3, 6, 3, 7, 3]
num = 3
print(f'Count of {num} has occurred {get_count(my_list, num)} times')

>>> Count of 3 has occurred 4 times

Method 2 - Using count function

def get_count(lst, num):
    return lst.count(num)
    
my_list = [2, 3, 5, 3, 6, 3, 7, 3]
num = 3
print(f'Count of {num} has occurred {get_count(my_list, num)} times')

>>> Count of 3 has occurred 4 times

Method 3 - Using counter function

from collections import Counter

def get_count(lst, num):
    return Counter(lst)[num]
    
my_list = [2, 3, 5, 3, 6, 3, 7, 3]
num = 3
print(f'Count of {num} has occurred {get_count(my_list, num)} times')

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe