To accomplish this task there many possible ways , I'll try to list here most of them.


  • 1- A simple approach : 
lets suppose that we want to find the number of occurrences of x in a list l, then the code using a for loop would be :

def countX(l, x):
count = 0
for i in l:
if (i == x): # check wether x is equal to i
count = count +
1 we increment the counter by one
return count

  • 2 - using count method : 
the count method gives directly the number of occurrences of x in l, the code in python would be : 

def countX(l, x):
return l.count(x)

  • 3 - using Counter method : 
This method gives us the occurrences of all the elements in the list, the code in python is : 

from collections import Counter #first we import the method
def countX(l,x) :
d = Counter(l) # d is a dictionary containing each number as a key and the
# number of occurrences as a value
return '{} has occurred {} times'.format(x, d[x])

  • 4 - using countOf method : 
This method can be used to get the occurrences of any element in a list, the code in python is : 
# import Operator module
import operator
def countX(l,x) :
count = operator.countOf(l, x) # gives the number of occurrences of x in l
return count
  • 5 - using a combination of lambda and map
Combination of lambda and map function can also do the job, the code in python is : 


def countX(l,x) :
a = sum(map(lambda v: v == x, l))
  • 6 - using the pandas module : 

You can use pandas, by transforming the list to a pd.Series then simply use .value_counts()

import pandas as pd
def countX(l,x) :
count = pd.Series(l).value_counts().to_dict()
return count[str(x)]





Sources : 
Buy Website Traffic