The crew is mapping the planets for a new display wall. Rocket has made a variable for each one: planet1, planet2, planet3, planet4. Now he wants to add four more.
"This is getting messy," he says. "And if I want to print them all, I have to name every single variable."
Raven lines up four cards on the desk, left to right. "What do you notice?" she asks. "They belong together, and their order matters. First, second, third."
Nova projects a long glowing shelf with numbered slots. "Would you like a hint?" she asks. "A list keeps many values under one name, in order. Each slot has a number, starting at zero."
Rocket replaces four variables with one list and grins.
A list is written with square brackets, with commas between the items. One name holds the whole list.
Each item has an index: its position number. Python counts from 0, so the first item is at index 0. Negative numbers count from the end, so index -1 is the last item.
len() tells you how many items a list has.
>>> planets = ["Mercury", "Venus", "Earth", "Mars"] >>> planets[0] 'Mercury' >>> planets[2] 'Earth' >>> planets[-1] 'Mars' >>> len(planets) 4 >>> planets[1] = "Venus (cloudy)" >>> planets ['Mercury', 'Venus (cloudy)', 'Earth', 'Mars']
You can change an item by storing a new value at its index, as the last example shows.
Asking for an index that does not exist gives an IndexError. A list of 4 items has indexes 0 to 3, so planets[4] is out of range.
>>> planets = ["Mercury", "Venus", "Earth", "Mars"] >>> planets[4] Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> IndexError: list index out of range
A slice takes a piece of a list. stations[1:3] gives the items from index 1 up to, but not including, index 3. It works just like range.
A slice gives you a new, shorter list. The original list stays the same.
# stations.py stations = ["Radar", "Fuel", "Comms", "Weather", "Medical"] print(stations[0]) print(stations[-1]) print(stations[1:3]) print(len(stations)) stations[2] = "Radio" print(stations)
Radar Medical ['Fuel', 'Comms'] 5 ['Radar', 'Fuel', 'Radio', 'Weather', 'Medical']
| Statement | True or false? |
|---|---|
| A list of 5 items has indexes 0 to 4. | ? |
| stations[5] gives the last item of a 5 item list. | ? |
| A slice changes the original list. | ? |
| len(stations) counts the items in the list. | ? |
One name can now hold a whole collection. Tomorrow you will add, remove and sort items.