
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – Restrict Elements Frequency in List
When it is required to restrict elements frequency in a list, a simple iteration is used along with the ‘append’ method.
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 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]
Explanation
The required packages are imported into the environment.
A list of integers is defined and is displayed on the console.
A dictionary is defined and displayed on the console.
An empty list is defined.
A default dictionary of integers is defined.
The original list is iterated over, and the dictionary elements are incremented by 1.
Depending on whether the element in the original dictionary and default dictionary are greater or not, the ‘continue’ operator is used.
Then, the ‘append’ method is used to add the element to the empty list.
This is the output that is displayed on the console.
- Related Articles
- List frequency of elements in Python
- Python – Fractional Frequency of elements in List
- Python - Restrict Tuples by frequency of first element’s value
- Find sum of frequency of given elements in the list in Python
- Matplotlib – Make a Frequency histogram from a list with tuple elements in Python
- Count minimum frequency elements in a linked list in C++
- Element with largest frequency in list in Python
- Finding frequency in list of tuples in Python
- Count Frequency of Highest Frequent Elements in Python
- Delete elements with frequency atmost K in Python
- Python – Count frequency of sublist in given list
- Delete List Elements in Python
- Python – Adjacent elements in List
- Python – List Elements Grouping in Matrix
- Find missing elements in List in Python

Advertisements