Skip to content

Python counts occurrences of an element in a list

  • by

A simple way is using the count() method to count occurrences of an element in a list in Python. However, there are six ways by which you can count the number of occurrences of the element in the list.

  • Using count() method
  • Using a loop
  • Using countof() method
  • Using pandas library
  • Using loops and dict in Python

Python counts occurrences of an element in a list

Simple example code using .count() list method, the Counter library, the pandas library, and dictionary comprehension.

count() method

l = ["a", "ab", "a", "abc", "ab", "ab"]

print('a', l.count("a"))
print('ab', l.count("ab"))

Output:

Python counts occurrences of an element in a list

Loop

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)))

countof() method

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

import operator as op

print(op.countOf(sample_list,"a")) 

counter() method

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]))

Pandas library

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

Using loops and dict

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

def countOccurrence(a):
  k = {}
  for j in a:
    if j in k:
      k[j] +=1
    else:
      k[j] =1
  return k

print(countOccurrence(sample_list))

Output: {‘a’: 2, ‘ab’: 3, ‘abc’: 1}

If you want to count occurrences of multiple elements, you may need to iterate through the list or use other techniques, such as using a dictionary to store counts. Here’s an example using a dictionary:

my_list = [1, 2, 3, 4, 1, 2, 1, 5]

# Count occurrences of each element in the list using a dictionary
element_counts = {}

for element in my_list:
    if element in element_counts:
        element_counts[element] += 1
    else:
        element_counts[element] = 1

print("Element counts:", element_counts)

Do comment if you have any doubts or suggestions on this Python list examples.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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