Replace List Elements

Replace all occurrences of a value in a list with another value.

PythonBeginner
Python
# Program to replace list elements

items = input("Enter list elements separated by space: ").split()
old = input("Enter value to replace: ")
new = input("Enter new value: ")

replaced = [new if x == old else x for x in items]

print("Updated list:", replaced)

Output

Enter list elements separated by space: a b a c
Enter value to replace: a
Enter new value: z
Updated list: ['z', 'b', 'z', 'c']

We use a list comprehension to selectively substitute one value for another.