Python: Replace duplicate values in a list with the same values

Question:

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]
Asked By: Cedric

||

Answers:

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]
Answered By: user

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])
Answered By: Sunil Rastogi

Among the fastest

fr = {x:0 for x in X}
for n in X:
    fr[n] += 1
Y = [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 change the value to 3 if it is repeated more than once.

Little bit slower and little bit shorter

xi = {x:i for i, x in enumerate(X)}
dp = {x: xi[x]>i for i, x in reversed(list(enumerate(X)))}
Y = [3 if dp[x] else x for x in X]

You iterate over X and keep the lastest index of each value. Then you iterate again but in reverse order, and ask if there is another index for that value. Then with that info you create the desired output. All using list/dict comprehension. This is more of a functional approach.

Answered By: nutax

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)
Answered By: Amin Javani

Maybe something like this:

X = [t if t not in X[:i] + X[i+1:] else 3 for i, t in enumerate(X)]
Answered By: MaryRa
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.