How to use Lambda Function In Python
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. Here we replace ‘Pant’ with ‘Ishan’ in the lambda function. Then using the list() function we convert the map object into the list.
Syntax: l=list(map(lambda x: x.replace(‘old_value’,’new_value’),l))
Python3
# Replace Values in a List using Lambda Function # define list l = [ 'Hardik' , 'Rohit' , 'Rahul' , 'Virat' , 'Pant' ] # replace Pant with Ishan l = list ( map ( lambda x: x.replace( 'Pant' , 'Ishan' ), l)) # print list print (l) |
Output:
['Hardik', 'Rohit', 'Rahul', 'Virat', 'Ishan']
How to Replace Values in a List in Python?
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 serval ways. Below are the methods to replace values in the list.
- Using list indexing
- Using for loop
- Using while loop
- Using lambda function
- Using list slicing
Contact Us