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


When it is required to remove tuples that have a duplicate first value from a given set of list of tuples, a simple 'for' loop, and the 'add' and 'append' methods can be used.

Below is a demonstration for the same −

Example

Live Demo

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

my_output_list = []
for a, b in my_input:
   if not a in visited_data:
      visited_data.add(a)
      my_output_list.append((a, b))

print("The list of tuple is : ")
print(my_input)
print("The list of tuple after removing duplicates is :")
print(my_output_list)

Output

The list of tuple is :
[(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')]
The list of tuple after removing duplicates is :
[(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]

Explanation

  • A list of tuple is defined, and is displayed on the console.
  • An empty set is created, as well as an empty list.
  • The list of tuple is iterated over, and if it is not present in the 'set', it is added to the set, as well as to the list.
  • This is the output that is displayed on the console.

Updated on: 13-Mar-2021

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements