1

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]
1
  • Create a set from X Y = set(X), then iterate through X and check if the value is contained in Y Commented Aug 2, 2022 at 18:07

5 Answers 5

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

This was a pretty simple one and uses basic list comprehension. 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])

1 Comment

I think they removed this answer because it only works for this case or only in cases where 2 is a duplicate value because it replaces the value 2 with the value 3. But if we want to replace duplicate values ​​that are not 2, unfortunately that won't work.
0

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]

Comments

0

Maybe something like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.