Given a list of elements and a value to replace, the task is to update one or more matching values with a new value. For Example:
Input: a = [10, 20, 30, 40, 50] and Replace value 30 -> 99
Output: [10, 20, 99, 40, 50]
Using List Indexing
This method replaces a value by directly accessing a specific position in the list and assigning a new value to that position. It works when the index of the element to be replaced is already known.
a = [10, 20, 30, 40, 50]
a[2] = 99
print(a)
Output
[10, 20, 99, 40, 50]
Explanation:
- a[2] accesses the element at index 2
- = assigns the new value 99
- The list a is updated in place
Using List Comprehension
This method checks every element in the list and replaces only those values that satisfy a given condition, while rebuilding the list in a single expression using list comprehension.
a = [10, 20, 30, 40, 50]
a = [99 if x == 30 else x for x in a]
print(a)
Output
[10, 20, 99, 40, 50]
Explanation:
- for x in a iterates over each element
- 99 if x == 30 else x replaces the value conditionally
- The updated elements are stored back in a
Using map() with lambda
This method goes through each element of the list and applies a small rule to it. The rule checks the value and replaces it only when the condition matches, otherwise the value remains the same.
a = [10, 20, 30, 40, 50]
a = list(map(lambda x: 99 if x == 30 else x, a))
print(a)
Output
[10, 20, 99, 40, 50]
Explanation:
- map() processes each element of a
- lambda x: 99 if x == 30 else x defines the replacement condition
- list() converts the result into a list
Using for Loop
This method walks through the list using index positions and replaces values whenever the specified condition is met during iteration with the help of for loop.
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]
Explanation:
- range(len(a)) generates index values
- a[i] accesses elements using indexes
- Assignment updates the matching value in the list