Skip to content
Advertisement

How to remove duplicates in a list of tuples

I have a list of tuples:

   exampleList = [("a", "januari", 10), ("b", "februari", 12), ("a", "februari", 12)]

   wantedList = [("a", "januari", 10), ("b", "februari", 12)]

So when the first item of the tuples in the list is double or more, i want to remove the duplicates. The end result has to be the wantedList. In a normal list i can do the “make a dictionary” trick but i dont know how to solve it with a list of tuples.

Advertisement

Answer

You can proceed with dict comprehension :

tmp_list = [("a", "januari", 10), ("b", "februari", 12), ("a", "februari", 12)]
tmp_dict = {elem[0]: elem for elem in tmp_list}

wanted_list = list(tmp_dict.values())

result is :

[('a', 'februari', 12), ('b', 'februari', 12)]

If you want to keep the first occurence, you can use reversed :

tmp_list = [("a", "januari", 10), ("b", "februari", 12), ("a", "februari", 12)]
tmp_dict = {elem[0]: elem for elem in reversed(tmp_list)}

wanted_list = list(tmp_dict.values())

Which gives you :

[('a', 'januari', 10), ('b', 'februari', 12)]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement