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
Selected Reading
Python – Extract elements with equal frequency as value
When it is required to extract elements with equal frequency as value, a list comprehension, the ‘count’ method and the ‘set’ operator are used.
Below is a demonstration of the same −
Example
my_list = [4, 1, 8, 6, 2, 4, 1, 3, 2, 4, 4]
print("The list is :")
print(my_list)
my_result = list(set([element for element in my_list if my_list.count(element) == element]))
print("The result is :")
print(my_result)
Output
The list is : [4, 1, 8, 6, 2, 4, 1, 3, 2, 4, 4] The result is : [2, 4]
Explanation
A list is defined and displayed on the console.
A list comprehension is used to iterate over the list, and the count of the element is compared to the element.
This converted to a set and then to a list.
This result is assigned to a variable.
This is the output that is displayed on the console.
Advertisements
