Python | Remove duplicate tuples from a list of tuples



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: Understanding list

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

# Python3 program for removing duplicates
# tuples from the 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))

Exit:

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

Method # 2: List Comprehension (Effective Approach)

This method is effective when compared to with the above method, here we use one for loop within a list comprehension and then convert it to a set to remove duplicates and then convert it back to a list again.

# Python3 duplicate remover
# tuples from a 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))

Exit :

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

Method # 3: method enums Python ()

# Python3 duplicate remover
# 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))

Exit:

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