VOOZH about

URL: https://www.geeksforgeeks.org/python/python-restrict-tuples-by-frequency-of-first-elements-value/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

Given a Tuple list, the task is to write a Python program to restrict the frequency of the 1st element of tuple values to at most K.

Examples:

Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 2

Output : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4), (4, 7)]

Explanation : 2 occurs 2 times in result list, (2, 5), the 3rd occurrence is omitted.

Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 3

Output : [(2, 3), (3, 3), (1, 4), (4, 7)]

Explanation : 2, 3, 1, 4 restricted to their 1st occurrence.

Method 1 : Using loop + keys() + conditional statements

In this, we perform task of memorizing count of each element of 1st position of tuples, and omit if its occurrences increases K.

Output:

The original list is : [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)]

Filtered tuples : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4), (4, 7)]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using defaultdict() + filter() + lambda

In this, we perform task of memorizing using defaultdict() and filter() and lambda functions are used for the task of checking and adding to result upon meeting of condition.

Output:

The original list is : [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)]

Filtered tuples : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4), (4, 7)]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. The defaultdict() + filter() + lambda is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n), new list of size O(n) is created where n is the number of elements in the list 

Comment