Replace List Elements in Python
Replace all occurrences of a value in a list with another value.
BeginnerList ProgramsExample 20 of 25
replace-list-elements.py
Run in browser1# Program to replace list elements23items = input("Enter list elements separated by space: ").split()4old = input("Enter value to replace: ")5new = input("Enter new value: ")67replaced = [new if x == old else x for x in items]89print("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']
What's going on
We use a list comprehension to selectively substitute one value for another.