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
Python – Restrict Elements Frequency in List
When it is required to restrict elements frequency in a list, we can use a simple iteration along with the append method and defaultdict to track element counts.
Example
Below is a demonstration of the same ?
from collections import defaultdict
my_list = [11, 14, 15, 14, 11, 14, 14, 15, 15, 16]
print("The list is :")
print(my_list)
my_dict = {14: 3, 11: 1, 16: 1, 15: 2}
print("The restrict dictionary is :")
print(my_dict)
my_result = []
my_def_dict = defaultdict(int)
for element in my_list:
my_def_dict[element] += 1
if my_def_dict[element] > my_dict[element]:
continue
else:
my_result.append(element)
print("The result is :")
print(my_result)
Output
The list is :
[11, 14, 15, 14, 11, 14, 14, 15, 15, 16]
The restrict dictionary is :
{14: 3, 11: 1, 16: 1, 15: 2}
The result is :
[11, 14, 15, 14, 14, 15, 16]
How It Works
The algorithm works by tracking the frequency of each element as we iterate through the list:
A defaultdict keeps count of how many times each element has been seen
For each element, we increment its count in the defaultdict
If the current count exceeds the allowed frequency from our restriction dictionary, we skip the element using
continueOtherwise, we add the element to our result list using
append
Alternative Approach Using Counter
Here's another way to achieve the same result using Counter ?
from collections import Counter
my_list = [11, 14, 15, 14, 11, 14, 14, 15, 15, 16]
restrictions = {14: 3, 11: 1, 16: 1, 15: 2}
result = []
element_count = Counter()
for element in my_list:
element_count[element] += 1
if element_count[element] <= restrictions[element]:
result.append(element)
print("The result is :")
print(result)
The result is : [11, 14, 15, 14, 14, 15, 16]
Conclusion
Use defaultdict or Counter to track element frequencies while iterating through a list. This approach allows you to restrict the number of times each element appears in the resulting list based on predefined limits.
