Method 6 Using functools.reduce method
Algorithm:
- Import reduce method from functools.
- initialize the test list.
- Use reduce method on the test list which checks for the element in the list and replaces it with new value.
- Print new list.
Python
# Replace Values in a List using reduce from functools import reduce # define list l = [ 'Hardik' , 'Rohit' , 'Rahul' , 'Virat' , 'Pant' ] # replace Rahul with Shikhar l = reduce ( lambda a, b : a + [ 'Shikhar' ] if b = = 'Rahul' else a + [b], l , []) # print list print (l) |
Output
['Hardik', 'Rohit', 'Shikhar', 'Virat', 'Pant']
Time complexity: O(N), where n is the length of the input List.
Auxiliary space: O(k), where k is the length of the new list with the new value.
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