← Back to course
Code Crew G4 / Week 02 / Friday
5/6
Week 02 Β· Lists

Friday

Add to the list
// Many values, one name
⏱ about 15 min

Friday: Add to the list

A new delivery drifts in: a roll of tape and a box of lamps. "Let's build it into the cargo list!" Rocket says. He types cargo[2] = "tape", and Python stops with an error.

Raven reads the error message out loud. "Index out of range. What do you notice? The list only has two items."

Rocket thinks. "So spot 2 does not exist yet." Nova spins once. "Would you like a hint? A list can grow. There is a command that adds to the end."

append adds to the end

append adds a new item to the end of a list. The list gets one item longer.

Write the list name, a dot, then append with the new item in brackets.

cargo = ["water", "oats"]
cargo.append("tape")
cargo.append("lamps")
print(cargo)
print(len(cargo))
The screen shows
['water', 'oats', 'tape', 'lamps']
4

Rocket's first try asked for index 2 when the list had only indexes 0 and 1. Python calls that an IndexError. It means the spot does not exist.

PUT THE LINES IN ORDER SO THE SCREEN SHOWS ['ROPE', 'CLAMP']
  • ?kit = []
  • ?kit.append("rope")
  • ?kit.append("clamp")
  • ?print(kit)
WHY THIS EXERCISEStarting with an empty list and appending is how programs collect things.
pods = [3, 7]
pods.append(5)
pods.append(9)
print(pods[-1])
print(len(pods))
First line on the screen
Second line on the screen
SPOT THE ERROR
  • Read the question.
  • Tap your answer.
A list has 3 items. Rocket writes print(cargo[3]). What happens?
At the computer
This is never required.
If a grown-up has installed Python from python.org, try today's cargo program in IDLE.
Add your own item with append.

Practice lab: grow a log

log = []
log.append("dock")
log.append("fuel")
log.append("launch")
print(log)
print(len(log))
print(log[0])
What does len(log) give at the end?
What does log[0] give?
What does log[-1] give?
APPEND OR ERROR?
  • Read the question.
  • Tap your answer.
kit = ["a"]. Then kit.append("b") runs. What is kit?
Where does append put the new item?
A list x has 2 items. Which line causes an IndexError?
StatementTrue or false?
append makes a list one item longer.?
append puts the new item at index 0.?
An IndexError means the spot does not exist.?
You can append to an empty list.?
WHY THIS EXERCISEappend grows a list safely. Setting an index that is not there causes an error.
pods = [1, 2]. Then pods.append(3) and pods.append(4) run. What does len(pods) give?
WHY THIS EXERCISEEach append makes the list one item longer.

Week two is done! You can make lists, read them, change them and grow them. Next week, you will loop through a whole list at once.

← Thursday