A message arrives from the supply ship. "Swap the oats for rice," it says. Rocket scrolls to the cargo list. "I need to change one item, and I need to check the last one too."
"The last one is easy," he says. "I just count to the end." But the list is long, and he loses his place twice.
Raven asks, "What do you notice about the end of every list?" Nova hums. "Would you like a hint? Python can count backward from the end too."
A negative index counts from the end. Index -1 is always the last item, however long the list is.
You can also change an item. Put the list name and index on the left of =.
cargo = ["water", "oats", "tools"] print(cargo[-1]) cargo[1] = "rice" print(cargo)
| The screen shows |
|---|
| tools |
| ['water', 'rice', 'tools'] |
Line 3 puts "rice" in index 1. The oats are replaced. The other items stay where they were.
fuel = [30, 45, 20, 50] fuel[0] = 35 print(fuel[0]) print(fuel[-1])
seats = ["Rocket", "Raven", "empty"] seats[2] = "Kai" print(seats)
Index -2 is the second item from the end. Negative indexes count backward from -1.
bay = ["oats", "rope", "lamp", "tape"] bay[0] = "rice" bay[-1] = "glue" print(bay) print(bay[-2])
| Statement | True or false? |
|---|---|
| Index -1 is always the last item. | ? |
| cargo[1] = "rice" adds a new item. | ? |
| Changing one item leaves the others alone. | ? |
| Index -1 is the first item. | ? |
Well done! You can reach the end of any list and swap items. Tomorrow you will add new items to a list.