How to Replace Values in a List in Python?
Published on Aug. 22, 2023, 12:15 p.m.
In Python, you can replace values in a list using various methods. Here are some common ways to accomplish this:
- Using indexing:
my_list = [1, 2, 3, 4, 5]
my_list[1] = 6 # replace the second element with 6
print(my_list) # Output: [1, 6, 3, 4, 5]
- Using list comprehension:
my_list = [1, 2, 3, 4, 5]
my_list = [6 if x == 2 else x for x in my_list] # replace all occurrences of 2 with 6
print(my_list) # Output: [1, 6, 3, 4, 5]
- Using the map() function:
my_list = [1, 2, 3, 4, 5]
my_list = list(map(lambda x: 6 if x == 2 else x, my_list)) # replace all occurrences of 2 with 6
print(my_list) # Output: [1, 6, 3, 4, 5]
In all these examples, we have a list called my_list
, and we either replace a specific element in the list or replace all occurrences of a particular value with a new value.
Note that modifying a list using indexing or list comprehension replaces the original list, while the map() function returns a new list object.