pythonlistfor-loopduplicates

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


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]

Solution

  • 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])