← Back to course
Code Crew G4 / Week 02 / Thursday
4/6
Week 02 Β· Lists

Thursday

The last item, and changes
// Many values, one name
⏱ about 15 min

Thursday: The last item, and changes

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."

Index -1 is the last item

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])
First line on the screen
Second line on the screen
seats = ["Rocket", "Raven", "empty"]
seats[2] = "Kai"
print(seats)
What does the program above show? Type the second name in the list.
WHY THIS EXERCISEChanging one index leaves every other item alone.
SAME OR DIFFERENT?
  • Read the question.
  • Tap your answer.
A list has 3 items. Which index also means the last item?
Try it
Write a list of three things you might pack for space.
Swap the middle item for something new.
Write the line of Python that makes the swap.

Practice lab: from the end

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])
After line 2, what is bay[0]?
After line 3, what is the last item?
What does line 5 show?
FRONT OR BACK?
  • Read the question.
  • Tap your answer.
fuel = [10, 20, 30]. What is fuel[-1]?
Which line changes the first item of cargo to "tea"?
A list has 5 items. Which index is the same item as -1?
StatementTrue 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.?
WHY THIS EXERCISESetting an index replaces one item. append is the tool that adds.
nums = [4, 9, 2]. Then nums[2] = 7 runs. What does print(nums[-1]) show?
WHY THIS EXERCISEnums[2] and nums[-1] are the same spot in a list of 3, so the 7 shows.

Well done! You can reach the end of any list and swap items. Tomorrow you will add new items to a list.

← Wednesday