Change List Items
Lists are mutable, which means we can change their items after creating them. Here’s how to update items using indexes and index ranges. Changing items from a list is easier; you just have to specify the index where you want to replace the item with a new value.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2] = "Millie"
print(names)Output:
['Harry', 'Sarah', 'Millie', 'Oleg', 'Steve']You can also change more than a single item at once. To do this, just specify the index range over which you want to change the items.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:4] = ["juan", "Anastasia"]
print(names)Output:
['Harry', 'Sarah', 'juan', 'Anastasia', 'Steve']What if the range of the index is more than the list of items provided?
In this case, all the items within the index range of the original list are replaced by the items that are provided.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[1:4] = ["juan", "Anastasia"]
print(names)Output:
['Harry', 'juan', 'Anastasia', 'Steve']What if we have more items to be replaced than the index range provided?
In this case, the original items within the range are replaced by the new items, and Python inserts all the new items and shifts the remaining elements to the right.
Example:
names = ["Harry", "Sarah", "Nadia", "Oleg", "Steve"]
names[2:3] = ["juan", "Anastasia", "Bruno", "Olga", "Rosa"]
print(names)Output:
['Harry', 'Sarah', 'juan', 'Anastasia', 'Bruno', 'Olga', 'Rosa', 'Oleg', 'Steve']