Python | Remove duplicate tuples from list of tuples

Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list.

Examples:

Input : [(1, 2), (5, 7), (3, 6), (1, 2)]
Output : [(1, 2), (5, 7), (3, 6)]

Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')]
Output : [('a', 'z'), ('a', 'x'), ('z', 'x')]

Method #1 : List comprehension



This is a naive approach to use list comprehension. Here, we use two for loops and set data structure to cancel out all the duplicates.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove duplicate 
# tuples from list of tuples
  
def removeDuplicates(lst):
      
    return [t for t in (set(tuple(i) for i in lst))]
          
# Driver code
lst = [(1, 2), (5, 7), (3, 6), (1, 2)]
print(removeDuplicates(lst))

chevron_right


Output:

[(1, 2), (5, 7), (3, 6)]

 
Method #2 : List comprehension (Efficient approach)

This method is efficient as compared to the above method, here we use a single for loop within list comprehension and then convert it to set to remove duplicates and then again convert it to list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove duplicate 
# tuples from list of tuples
  
def removeDuplicates(lst):
      
    return list(set([i for i in lst]))
          
# Driver code
lst = [(1, 2), (5, 7), (3, 6), (1, 2)]
print(removeDuplicates(lst))

chevron_right


Output:

[(1, 2), (5, 7), (3, 6)]

 
Method #3 : Python enumerate() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove duplicate 
# tuples from list of tuples
  
def removeDuplicates(lst):
      
    return [[a, b] for i, [a, b] in enumerate(lst) 
    if not any(c == b for _, c in lst[:i])]
          
# Driver code
lst = [(1, 2), (5, 7), (3, 6), (1, 2)]
print(removeDuplicates(lst))

chevron_right


Output:

[[1, 2], [5, 7], [3, 6]]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ManasChhabra2