Python – Extract elements with equal frequency as value

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 06-Sep-2021 08:04:40
Advertisements