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
Find sum of frequency of given elements in the list in Python
When working with lists containing repeated elements, we often need to find the sum of frequencies for specific items. Python provides several approaches to calculate this efficiently ?
Using sum() with count()
This method uses the built-in count() method to find frequency of each element and sum() to calculate the total ?
chk_list = ['Mon', 'Tue']
big_list = ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
# Apply sum
res = sum(big_list.count(elem) for elem in chk_list)
# Printing output
print("Given list to be analysed:")
print(big_list)
print("Given list with values to be analysed:")
print(chk_list)
print("Sum of the frequency:", res)
Given list to be analysed: ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue'] Given list with values to be analysed: ['Mon', 'Tue'] Sum of the frequency: 5
Using collections.Counter
The Counter class from the collections module provides a more efficient approach by counting all elements once, then looking up frequencies ?
from collections import Counter
chk_list = ['Mon', 'Tue']
big_list = ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
# Apply Counter
counter = Counter(big_list)
res = sum(counter[x] for x in chk_list)
# Printing output
print("Given list to be analysed:")
print(big_list)
print("Given list with values to be analysed:")
print(chk_list)
print("Sum of the frequency:", res)
Given list to be analysed: ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue'] Given list with values to be analysed: ['Mon', 'Tue'] Sum of the frequency: 5
Example with Numbers
Here's another example using numeric values to demonstrate the concept ?
from collections import Counter
numbers = [1, 2, 3, 1, 2, 1, 4, 5, 2]
target_numbers = [1, 2]
# Method 1: Using sum and count
freq_sum1 = sum(numbers.count(num) for num in target_numbers)
# Method 2: Using Counter
counter = Counter(numbers)
freq_sum2 = sum(counter[num] for num in target_numbers)
print("Numbers list:", numbers)
print("Target numbers:", target_numbers)
print("Sum of frequencies (Method 1):", freq_sum1)
print("Sum of frequencies (Method 2):", freq_sum2)
Numbers list: [1, 2, 3, 1, 2, 1, 4, 5, 2] Target numbers: [1, 2] Sum of frequencies (Method 1): 6 Sum of frequencies (Method 2): 6
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
sum() with count() |
O(n × m) | Small lists, simple implementation |
collections.Counter |
O(n + m) | Large lists, multiple queries |
Conclusion
Use sum() with count() for simple cases with small lists. For better performance with large datasets or multiple frequency queries, collections.Counter is the preferred approach as it counts elements only once.
