Replace List Elements

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

BeginnerTopic: List Programs
Back

Python Replace List Elements Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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']

Understanding Replace List Elements

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents