Python | Counting occurrences of an item in a list

Counters | Python Methods and Functions

Examples:

 Input: lst = [15, 6, 7, 10, 12, 20, 10, 28, 10] x = 10 Output: 3 10 appears three times in given list. Input: lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 16 Output: 0 

Method 1 (Simple Approach)

# Python code to count the number of occurrences

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

 Output: 8 has occurred 5 times 

Method 2 (Using count ())
The idea is to use list () method to count the number of occurrences.

# Python code to count the number of occurrences

def countX (lst, x):

  return lst.count (x)

 
Code driver

lst = [ 8 , 6 , 8 , 10 , 8 , 20 , 10 , 8 , 8 ]

x = 8

print ( '{} has occurred {} times' . format (x, countX (lst, x)))

 Output: 8 has occurred 5 times 

Method 2 (using counter ())
The Counter method returns a dictionary with entries of all elements as a key-value pair, where key — it is an element, and value — the number of times this element has been encountered.

from collections import Counter

  
# list declaration

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

 Output: 3 has occurred 2 times 




Get Solution for free from DataCamp guru