Python - Restrict Tuples by frequency of first element's value

When working with lists of tuples, you may need to restrict tuples based on how frequently their first element appears. This technique is useful for filtering duplicates or limiting occurrences to a specific threshold.

Example

Below is a demonstration of restricting tuples by frequency of the first element ?

my_list = [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83), (13, 27)]

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

my_key = 1

my_result = []
mems = dict()
for sub in my_list:
    if sub[0] not in mems.keys():
        mems[sub[0]] = 1
    else:
        mems[sub[0]] += 1
    if mems[sub[0]] <= my_key:
        my_result.append(sub)

print("The filtered tuples are :")
print(my_result)
The list is :
[(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83), (13, 27)]
The filtered tuples are :
[(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83)]

How It Works

The algorithm works by maintaining a frequency counter for first elements ?

  • A list of tuples is defined and displayed on the console.

  • The frequency threshold my_key is set to 1 (allowing each first element to appear only once).

  • An empty result list and dictionary are created for storing results and tracking frequencies.

  • For each tuple, if its first element hasn't been seen, initialize its count to 1 in the dictionary.

  • If the first element already exists, increment its count by 1.

  • Only add the tuple to results if its first element's frequency is within the allowed threshold.

  • The second occurrence of tuple (13, 27) is filtered out because 13 already appeared once.

Alternative Using Collections Counter

A more concise approach using collections.Counter ?

from collections import Counter

my_list = [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83), (13, 27)]
my_key = 1

counter = Counter()
result = []

for tup in my_list:
    counter[tup[0]] += 1
    if counter[tup[0]] <= my_key:
        result.append(tup)

print("Filtered tuples:", result)
Filtered tuples: [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83)]

Conclusion

This technique efficiently filters tuples by tracking first element frequencies. Use a dictionary for basic frequency counting or collections.Counter for cleaner code when working with frequency-based filtering.

Updated on: 2026-03-26T02:07:44+05:30

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements