 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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. 
Advertisements
 