This concise, example-based article gives you some solutions to replace or update elements in a list in Python.
Using indexing or slicing
If you want to update or replace a single element or a slice of a list by its index, you can use direct assignment with the []
operator. This is usually the simplest and fastest way to modify a list element or slice.
Example:
# create a list of numbers
my_list = [1, 2, 3, 4, 5]
print(my_list)
# [1, 2, 3, 4, 5]
# replace the second element with 10 using indexing
my_list[1] = 10
print(my_list)
# [1, 10, 3, 4, 5]
# replace the last two elements with 6 and 7 using slicing
my_list[-2:] = [6, 7]
print(my_list)
# [1, 10, 3, 6, 7]
This approach doesn’t create a new list but changes the original list.
Using list comprehension
If you want to update or replace multiple elements in a list based on a condition or a function, you can use list comprehension to create a new list with the updated or replaced elements. This is usually more concise and readable than other approaches. However, it may also create a new list object in memory, which may be less efficient than modifying the original list in place.
Code example:
# create a list
my_list = [1, 2, 3, 4, 5]
# create a new list with all even numbers doubled using list comprehension
new_my_list = [x * 2 if x % 2 == 0 else x for x in my_list]
print(f"The original list: {my_list}")
print(f"The new list: {new_my_list}")
Output:
The original list: [1, 2, 3, 4, 5]
The new list: [1, 4, 3, 8, 5]
With this approach, the original list is intact.
Using the enumerate() function
If you want to update or replace multiple elements in a list in place (without creating a new list) based on a condition or a function, you can use the enumerate()
function to loop over the list and get both the index and the value of each element. Then, you can use direct assignment to modify the element in the original list. This may be more efficient than creating a new list object in memory. However, it may also be less concise and readable than using a list comprehension.
Example:
# create a list of letters
my_list = ["blue", "red", "green", "orange", "yellow", "purple"]
for index, value in enumerate(my_list):
# if index is even or the length of the value is less than 5
# replace the value with an asterisk
if index % 2 == 0 or len(value) < 5:
my_list[index] = "*"
print(my_list)
Output:
['*', '*', '*', 'orange', '*', 'purple']
Use a for loop or a while loop
You can also use a for
loop or a while
loop instead of the enumerate()
function. However, the code will be a little bit longer.
Example (for
loop):
# create a list of words
my_list = ["caramel", "chocolate", "vanilla", "strawberry", "mint"]
# capitalize the first letter of words whose length is greater than 7
for i in range(len(my_list)):
if len(my_list[i]) > 7:
my_list[i] = my_list[i].capitalize()
print(my_list)
Output:
['caramel', 'Chocolate', 'vanilla', 'Strawberry', 'mint'
Another example (white
loop):
import pprint
employees = [
{
"name": "Wolf",
"salary": 50000,
},
{
"name": "Turtle",
"salary": 60000,
},
{
"name": "Demon of the Abyss",
"salary": 65000,
}
]
# using a while loop to update the salary of each employee (+20%)
i = 0
total_employees = len(employees)
while i < total_employees:
employees[i]["salary"] = employees[i]["salary"] * 1.2
i += 1
pprint.pprint(employees)
Output:
[{'name': 'Wolf', 'salary': 60000.0},
{'name': 'Turtle', 'salary': 72000.0},
{'name': 'Demon of the Abyss', 'salary': 78000.0}]
pprint
is a standard module of Python. I used it in the example above just to make the output easier to read. You can use the print()
function if you don’t care how your output looks.