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 −
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)
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')