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 browser
1# Program to replace list elements
2
3items = input("Enter list elements separated by space: ").split()
4old = input("Enter value to replace: ")
5new = input("Enter new value: ")
6
7replaced = [new if x == old else x for x in items]
8
9print("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.