Remove tuples having duplicate first value from given list of tuples in Python

When removing tuples with duplicate first values from a list of tuples, you can use a set to track visited first elements. This approach preserves the first occurrence of each unique first value.

Using Set to Track First Values

The most efficient approach uses a set to remember which first values have been seen ?

tuples_list = [(45.324, 'Hi Jane, how are you'),
               (34252.85832, 'Hope you are good'), 
               (45.324, 'You are the best.')]

visited_data = set()
result = []

for first, second in tuples_list:
    if first not in visited_data:
        visited_data.add(first)
        result.append((first, second))

print("Original list of tuples:")
print(tuples_list)
print("After removing duplicates:")
print(result)
Original list of tuples:
[(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')]
After removing duplicates:
[(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]

Using Dictionary (Alternative Method)

You can also use a dictionary to store the first occurrence of each first value ?

tuples_list = [(1, 'apple'), (2, 'banana'), (1, 'orange'), (3, 'grape')]

unique_dict = {}
for first, second in tuples_list:
    if first not in unique_dict:
        unique_dict[first] = second

result = list(unique_dict.items())
print("Original list:", tuples_list)
print("Unique tuples:", result)
Original list: [(1, 'apple'), (2, 'banana'), (1, 'orange'), (3, 'grape')]
Unique tuples: [(1, 'apple'), (2, 'banana'), (3, 'grape')]

How It Works

  • The set visited_data keeps track of first values already seen
  • For each tuple, we check if its first element is in the visited set
  • If not seen before, we add it to both the set and result list
  • This preserves only the first occurrence of each unique first value

Comparison

Method Time Complexity Space Complexity Best For
Set approach O(n) O(k) Just removing duplicates
Dictionary approach O(n) O(k) When you need the values too

where n = total tuples, k = unique first values

Conclusion

Use a set to efficiently track visited first values when removing tuple duplicates. This approach has O(n) time complexity and preserves the first occurrence of each unique tuple.

Updated on: 2026-03-25T17:42:29+05:30

689 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements