Replace duplicates in tuple in Python



When it is required to replace the duplicates in a tuple with a different value, a 'set' method and the list comprehension 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 = (11, 14, 0, 78, 33, 11, 10, 78, 0)

print("The tuple is : ")
print(my_tuple_1)
my_set = set()

my_result = tuple(ele if ele not in my_set and not my_set.add(ele)
   else 'FILL' for ele in my_tuple_1)
print("The tuple after replacing the values is: ")
print(my_result)

Output

The tuple is :
(11, 14, 0, 78, 33, 11, 10, 78, 0)
The tuple after replacing the values is:
(11, 14, 0, 78, 33, 'FILL', 10, 'FILL', 'FILL')

Explanation

  • A tuple is defined and is displayed on the console.
  • Another empty set is created.
  • The tuple is iterated over, and elements are appended to list only if they are not already present in the list.
  • If they are present, it is replaced with the value 'FILL'.
  • This is now converted to a tuple.
  • This is assigned to a value.
  • It is displayed on the console.

Advertisements