"Rocket, can you pass me the first item on the cargo list?" Raven asks. Rocket opens the list and grabs spot number one. Out floats a bag of oats.
"I wanted the water," Raven laughs. "What do you notice about how Python numbers the spots?"
Rocket frowns at the screen. The water is at the very front. So why did spot one give him oats?
Nova blinks. "Interesting. Would you like a hint? Python starts counting at a number smaller than one."
Each item in a list has a spot number called an index.
Python starts counting at 0. So the first item is at index 0.
To get one item, write the list name, then the index in square brackets.
cargo = ["water", "oats", "tools", "lamps"] print(cargo[0]) print(cargo[2])
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Item | water | oats | tools | lamps |
| The screen shows |
|---|
| water |
| tools |
Rocket asked for spot 1, so he got the second item. That is why the oats floated out.
launches = ["Mars run", "Moon hop", "Ring tour"] print(launches[1])
moons = ["Pip", "Zed", "Ula", "Bix"] print(moons[0]) print(moons[3]) print(moons[1])
| Statement about the moons list | True or false? |
|---|---|
| moons[0] is "Pip". | ? |
| moons[4] is "Bix". | ? |
| moons[2] is "Ula". | ? |
| moons[1] is "Pip". | ? |
Counting from zero feels odd at first, and you did it! Tomorrow you will count how many items a list holds.