Python Count Occurrence Of Elements

There are several ways to count the occurrence of elements in a Python list. One way is to use the list.count() method which takes an element as an argument and returns the number of times it appears in the list. For example:

a = [1, 2, 3, 4, 1, 2, 1]
b = a.count(1) # b is 3
c = a.count(5) # c is 0

Another way is to use a loop and a counter variable to iterate over the list and increment the counter whenever the element is found. For example:

a = [1, 2, 3, 4, 1, 2, 1]
x = 1
count = 0
for ele in a:
    if ele == x:
        count += 1

# count is 3 

A third way is to use a dictionary or a defaultdict to store the elements as keys and their counts as values. For example:

from collections import defaultdict

a = [1, 2, 3, 4, 1 ,2 ,1]
occurrence = defaultdict(lambda:0)
for ele in a:
    occurrence[ele] += 1

# occurrence is {1:3 ,2:2 ,3:1 ,4:1}

It is good to have an idea of the number of times elements occurred in your data structure.

from collections import Counter
data= [96,95,96,87,87,88,56,57,57]occurences = Counter(data)
print(occurences)

# output Counter({96: 2, 87: 2, 57: 2, 95: 1, 88: 1, 56: 1})

If you have any questions about this code, you can drop a line in comment.

 

Comments

Popular posts from this blog

Python chr() Built in Function

Python float() Built in Function

Python bool() Built in Function

Python Printing Readable Results

Python exec() Built in Function