Program to count the number of occurrence of element in the list using Python

by | Jan 22, 2021 | Python Programs

Home » Python » Python Programs » Program to count the number of occurrence of element in the list using Python

Introduction

In this section of python programming, we will understand different ways to count the occurrence of the given value in the list. Python provides two in-built functions to count the occurrences: count() and Counter().

The difference between count and Counter() is that, Counter() returns the value as key and value pairs. The key stores the element value and value stores the number of occurrences.

Instead of using python in-built function, we can also use the simple method to count the number of occurrence of the given element. In this method, the counter increases every time the value is found.

Program to count the number of occurrence of element in the list

Program

from collections import Counter
list = [1, 2, 3, 1, 5, 6, 2, 3, 1]
print(list)
element = int(input("Enter the value to find the occurrence: "))
# Using count()
n = list.count(element)
print("Number of occurrence of {0} using count() is {1}".format(element,n))
#Using counter()
d = Counter(list)
print("Number of occurrence of {0} using Counter() is {1}".format(element,d[element]))
# Display key value pair
print("Display key value pair",d)

 

Output

Program to count the number of occurrence of element in the list Output

Explanation

In the above python code we have used count() and Counter() to count the number of occurrences of integer in the list. The input is stored in the variable element; variable n and d stores the count values.

From the output we can observe that if we do not provide the specific key to the variable d, the whole key-value pair corresponding to the list is printed out. Whereas, when we have given the specific key (i.e. 2) while printing, the value corresponding to the key 2 is only displayed.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author