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. This technique finds elements where the number of times they appear in the list equals their actual value.

For example, if the number 4 appears exactly 4 times in the list, or 2 appears exactly 2 times, these elements would be extracted.

Example

Below is a demonstration of extracting elements with equal frequency as value ?

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]

How It Works

Let's break down the frequency analysis for each element ?

my_list = [4, 1, 8, 6, 2, 4, 1, 3, 2, 4, 4]

print("Element : Frequency : Equal?")
print("-" * 25)

for element in set(my_list):
    frequency = my_list.count(element)
    is_equal = frequency == element
    print(f"{element:7} : {frequency:9} : {is_equal}")
Element : Frequency : Equal?
-------------------------
1       :         2 : False
2       :         2 : True
3       :         1 : False
4       :         4 : True
6       :         1 : False
8       :         1 : False

Alternative Method Using Dictionary

A more efficient approach for larger lists uses a dictionary to count frequencies ?

from collections import Counter

my_list = [4, 1, 8, 6, 2, 4, 1, 3, 2, 4, 4]

print("The list is :")
print(my_list)

# Count frequencies using Counter
freq_count = Counter(my_list)

# Extract elements where frequency equals value
result = [element for element, frequency in freq_count.items() if frequency == element]

print("The result is :")
print(result)
The list is :
[4, 1, 8, 6, 2, 4, 1, 3, 2, 4, 4]
The result is :
[4, 2]

Comparison

Method Time Complexity Best For
List Comprehension + count() O(n²) Small lists, simple syntax
Counter Dictionary O(n) Large lists, better performance

Conclusion

Use list comprehension with count() for simple cases, or Counter for better performance. Both methods effectively extract elements whose frequency matches their value in the list.

Updated on: 2026-03-26T01:02:45+05:30

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements