Python Program to Search the Number of Times a Particular Number Occurs in a List

PythonServer Side ProgrammingProgramming

When it is required to search the frequency of a number in a list, a method is defined, that takes a list and the number. It iterates through the list, and every time the number is encountered, the counter is incremented.

Below is the demonstration of the same −


 Live Demo

def count_num(my_list, x_val):
   my_counter = 0
   for elem in my_list:
      if (elem == x_val):
         my_counter = my_counter + 1
   return my_counter

my_list = [ 66, 26, 48, 140, 66, 20, 1, 96, 86]
print("The list is :")
occ_number = 66
print('{} has occurred {} times'.format(occ_number, count_num(my_list, occ_number)))


The list is :
[66, 26, 48, 140, 66, 20, 1, 96, 86]
66 has occurred 2 times


  • A method named ‘count_number’ is defined, that takes a list and a number as parameter.

  • The list is iterated over, and if any element matches the number, the counter is incremented.

  • The counter is returned as result of the function.

  • Outside the function, a list is defined, and is displayed on the console.

  • The number is defined, and the method is called by passing these parameters.

  • The output is displayed on the console.

Updated on 19-Apr-2021 10:48:29