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



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 −

Example

 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 :") print(my_list) occ_number = 66 print('{} has occurred {} times'.format(occ_number, count_num(my_list, occ_number)))

Output

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

Explanation

  • 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: 2021-04-19T10:48:29+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements