How to Count the Occurrences of a element in a List in Python?

Spread the love

Problem –

You want to count the occurences of an element in a list in python.

Solution –

Count occurrences of an item in a list in Python –

If you want to count the occurrences of a single item in a list then use the built in list count method.

In [1]: nums = [1, 6, 1, 3, 1, 6, 8, 1] 

In [2]: # how many times 1 appears in the list

In [3]: nums.count(1)
Out[3]: 4

In [4]: # how many times 6 appears in the list

In [5]: nums.count(6)
Out[5]: 2

In [6]: # how many times 100 appears in the list

In [7]: nums.count(100)
Out[7]: 0

Count the Occurrences of every item in the List –

If you want to count the occurrences of every items in the list then use counter from collection module.

In [1]: nums = [1, 6, 1, 3, 1, 6, 8, 1]

In [2]: from collections import Counter

In [3]: Counter(nums)
Out[3]: Counter({1: 4, 6: 2, 3: 1, 8: 1})

Rating: 1 out of 5.

Leave a Reply