Python Change List Items
Because lists are mutable, you can replace one item, overwrite an entire range of items, or update them while looping.
Changing a single item
Assign a new value to a specific index to replace what was there before. The list keeps its length and order; only the targeted position changes. This works because a list is mutable, meaning its contents can be edited in place without creating a new object.
Replacing by index
scores = [10, 20, 30, 40]
scores[1] = 99
print(scores)After the assignment, the list becomes [10, 99, 30, 40]. Only the value at index 1 was swapped out, while every other item stayed exactly where it was.
Changing a range of items
You can also assign to a slice to replace several items at once. The number of new values does not have to match the number of items you are replacing, so a slice assignment can shrink or grow the list depending on how many values you provide.
Replacing a slice
letters = ["a", "b", "c", "d"]
letters[1:3] = ["x", "y", "z"]
print(letters)The slice letters[1:3] covered 'b' and 'c'. Replacing it with three values produces ['a', 'x', 'y', 'z', 'd'], so the list grew by one item because more values went in than came out.
- list[i] = value replaces exactly one item.
- list[a:b] = [...] replaces a whole section and may change the list length.
- Looping with range(len(list)) lets you update each item using its index.
Updating during a loop
prices = [100, 200, 300]
for i in range(len(prices)):
prices[i] = prices[i] * 2
print(prices)