Open In App

How to Replace Values in a List in Python?

Last Updated : 04 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Replacing values in a list in Python can be done by accessing specific indexes and using loops. In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in several ways. The simplest way to replace values in a list in Python is by using list indexing.

Let’s take an example of replacing values in a list using list indexing.

a = [10, 20, 30, 40, 50]

# Replacing 30 to 99
a[2] = 99
print(a)

Output
[10, 20, 99, 40, 50]

Let’s see other different methods to Replace Values in a List.

Using Lambda Function

In this method, we use lambda and map function to replace the value in the list. map() is a built-in function in python to iterate over a list without using any loop statement. A lambda is an anonymous function in python that contains a single line expression. Here we gave one expression as a condition to replace value.

a = [10, 20, 30, 40, 50]
b = list(map(lambda x: 99 if x == 30 else x, a))

print(b)

Output
[10, 20, 99, 40, 50]

Using For Loop

We can use for loop to iterate over the list and replace values in the list. We first find values in the list using for loop and if condition and then replace it with the new value. 

a = [10, 20, 30, 40, 50]

for i in range(len(a)):
    if a[i] == 30:
        a[i] = 99

print(a)

Output
[10, 20, 99, 40, 50]

Using While Loop

We can also use a while loop to replace values in the list. While loop does the same work as for loop. In the while loop first, we define a variable with value 0 and iterate over the list. If value matches to value that we want to replace then we replace it with the new value.

a = [10, 20, 30, 40, 50]
i = 0
while i < len(a):
    if a[i] == 30:
        a[i] = 99
    i += 1

print(a)

Output
[10, 20, 99, 40, 50]



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg