+

Python | Replace duplicates in a tuple

Method # 1: Using set () + List Comprehension
A combination of the above functions can be used to accomplish this particular task. In this case, we simply initialize the collection container and then replace the duplicate elements with a value by checking its existence in the tuple.

# Python3 demo code
# Replace duplicates in tuple
# using set () + list comprehension

 
# initialize tuple

test_tup = ( 1 , 1 , 4 , 4 , 4 , 5 , 5 , 6 , 7 , 7 )

 
# print the original tuple

print ( "The original tuple is:" + str (test_tup))

 
# Replace duplicate tuples
# using set () + list comprehension

temp = set ()

res =  tuple (ele if ele not in temp and not temp.add (ele) 

else `gfg` for ele in test_tup)

 
# print result

print ( "Tuple after replacing values:" + str (res))

Output:

 The original tuple is: (1, 1, 4, 4, 4, 5, 5, 6, 7, 7) Tuple after replacing values: (1, `gfg`, 4,` gfg`, `gfg`, 5,` gfg`, 6, 7, `gfg`) 

Method # 2: Using groupby () + loop
Combining the above functions can be solved with this problem. In doing so, we simply group consecutive elements, and then replace every element except the 1st one with the default value. Works only in case of consecutive duplicates.

# Python3 code to demonstrate how it works
# Replace duplicates in a tuple
# using groupby () + loop

from itertools import groupby

  
# initialize the tuple

test_tup = ( 1 , 1 , 4 , 4 , 4 , 5 , 5 , 6 , 7 , 7 )

 
# print original tuple

print ( "The original tuple is:" + str (test_tup))

 
# Replace duplicates in tuple
# using groupby () + loop

res = tuple ()

for < code class = "plain"> key, ele in groupby (test_tup):

res = res + ((key,) + ( `gfg` ,) * ( len ( list (ele)) - 1 ))

  
# print result

print ( "Tuple after replacing values:" + str (res))

Output:

 The original tuple is: (1, 1, 4, 4, 4, 5, 5, 6, 7, 7) Tuple after replacing values: (1 , `gfg`, 4,` gfg`, `gfg`, 5,` gfg`, 6, 7, `gfg`) 
Get Solution for free from DataCamp guru