Home > Software engineering >  Python: Replace duplicate values in a list with the same values
Python: Replace duplicate values in a list with the same values

Time:08-03

I have a list and would like to convert all duplicates values to 3 without changing the order and without importing any packages

X = [1, 2, 2, 5, 4, 8, 6]

Desired output:

X = [1, 3, 3, 5, 4, 8, 6]

CodePudding user response:

This code automatically replace all duplicate items with 3

my_list = [1, 2, 2, 5, 4, 8, 6]
new = []
for item in my_list:
   if my_list.count(item) > 1:
    new.append(3)
   else:
    new.append(item)
print(new)

CodePudding user response:

Not sure why another user deleted their answer but that was a pretty simple one and uses basic list comprehension. So I am bringing the same to you. Please refer the code below for same:

X = [1, 2, 2, 5, 4, 8, 6]
print([3 if e==2 else e for e in X])

CodePudding user response:

You should be able to use a for loop for this

my_list = [1, 2, 2, 5, 4, 8, 6]
new_list = []

for i in range(len(my_list)):
    if my_list[i] in new_list:
        new_list.append(3)
    else:
        new_list.append(my_list[i])
print(new_list)

Output:

 [1, 3, 3, 5, 4, 8, 6]

CodePudding user response:

Maybe something like this:

X = [t if t not in X[:i]   X[i 1:] else 3 for i, t in enumerate(X)]

CodePudding user response:

fr = {x:0 for x in X}
for n in X:
    fr[n]  = 1
X = [3 if fr[n]>1 else n for n in X]

You iterate over the list and add one to the dictionary counter for that number. Then you create a list with list comprehension: you modify the value to 3 if it is repeated more than once.

  • Related