Changing List Elements
You can also change an element of a list. Write the list's name and the index in square brackets, as when you read the element, and assign it a new value with =, just as you would assign a value to a variable:
resolutions = ["Keep a diary", "Take a falconry course", "Learn to juggle"]
resolutions[1] = "Take a painting course"
print(resolutions)This prints:
['Keep a diary', 'Take a painting course', 'Learn to juggle']The element at index 1 now has a new value, and the old one is gone. The other elements stay as they were. An element of a list works like a variable, so += works too: scores[0] += 5 adds 5 to the first element of the list scores.
You can only change an element that exists. Assigning to an index past the end of the list doesn't add a new element:
numbers = [1, 2, 3]
numbers[3] = 4The program ends with this error:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
IndexError: list assignment index out of rangeThis time, the error message talks about a list assignment index: the index you assigned a value to. You'll learn how to add an element to the end of a list in a moment.
Instructions
- 1
Tim has moved to another team, and Daniel has taken his place. Below the
print(), change the second element ofcolleaguesto"Daniel". - 2
Then print
colleaguesagain. The output now shows the list before and after the change.