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
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.

After this program

If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.