Remove duplicate lists in tuples (Preserving Order) in Python


When it is required to remove the duplicates present in tuple of list, as well as preserving the order, a list comprehension and the 'set' method can be used.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

Python comes with a datatype known as 'set'. This 'set' contains elements that are unique only. The set is useful in performing operations such as intersection, difference, union and symmetric difference.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = ([1, 21, 34] , [11, 0, 98], [45, 67, 56])

print("The tuple of list is : ")
print(my_tuple_1)
temp_val = set()

my_result = [elem for elem in my_tuple_1 if not(tuple(elem) in temp_val or temp_val.add(tuple(elem)))]
print("The unique tuple of list is : ")
print(my_result)

Output

The tuple of list is :
([1, 21, 34], [11, 0, 98], [45, 67, 56])
The unique tuple of list is :
[[1, 21, 34], [11, 0, 98], [45, 67, 56]]

Explanation

  • A tuple of list is defined, and is displayed on the console.
  • An empty set is created.
  • The tuple of list is iterated over, and if it is not present in the previously defined list, it is added to the list.
  • This would result in a set that contains unique values.
  • This is assigned to a value.
  • It is displayed on the console.

Updated on: 12-Mar-2021

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements