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 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.
pods = [3, 7] pods.append(5) pods.append(9) print(pods[-1]) print(len(pods))
log = []
log.append("dock")
log.append("fuel")
log.append("launch")
print(log)
print(len(log))
print(log[0]) | Statement | True 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. | ? |
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.