Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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, Python provides multiple approaches. You can define a custom method, use the built-in count() method, or utilize dictionary-based counting with collections.Counter.
Method 1: Using Custom Function
Define a function that iterates through the list and counts occurrences ?
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)))
The list is : [66, 26, 48, 140, 66, 20, 1, 96, 86] 66 has occurred 2 times
Method 2: Using Built-in count() Method
The simplest approach is using the list's built-in count() method ?
my_list = [66, 26, 48, 140, 66, 20, 1, 96, 86]
occ_number = 66
count = my_list.count(occ_number)
print(f"The list is: {my_list}")
print(f"{occ_number} has occurred {count} times")
The list is: [66, 26, 48, 140, 66, 20, 1, 96, 86] 66 has occurred 2 times
Method 3: Using collections.Counter
For counting all elements at once, use Counter from the collections module ?
from collections import Counter
my_list = [66, 26, 48, 140, 66, 20, 1, 96, 86]
counter = Counter(my_list)
print(f"The list is: {my_list}")
print(f"All element frequencies: {dict(counter)}")
print(f"66 has occurred {counter[66]} times")
The list is: [66, 26, 48, 140, 66, 20, 1, 96, 86]
All element frequencies: {66: 2, 26: 1, 48: 1, 140: 1, 20: 1, 1: 1, 96: 1, 86: 1}
66 has occurred 2 times
Comparison
| Method | Best For | Time Complexity |
|---|---|---|
| Custom Function | Learning purposes | O(n) |
count() |
Single element counting | O(n) |
Counter |
Multiple element counting | O(n) |
Conclusion
Use the built-in count() method for simple frequency counting. Use collections.Counter when you need to count frequencies of all elements simultaneously.
Advertisements
