Track: Python for Kids · Lesson 7 of 10 · Ages: 8+ · Time: 35 minutes
A variable holds one thing. But what if you want to remember a whole bunch of things, like everything in your backpack? You could make a hundred variables, but that would be silly. Python has a better idea: the list.
Beep says My backpack holds a torch, a map and a spare battery. One backpack, three things. A list is a backpack for your program! Beep boop!
What you need
- Python and IDLE.
- A new file called
backpack.py.
Grown-ups Lists are the first data structure children meet. The thing that trips up almost everyone is that positions start at 0, not 1. Using a real-life picture (a row of numbered pegs that starts at peg 0) helps. If a child sees an IndexError, they have asked for a position that does not exist.
Making a list
A list is written between square brackets [ ], with commas between the items:
backpack = ["torch", "map", "sandwich"]
print(backpack)
print(len(backpack))
['torch', 'map', 'sandwich'] 3
When Python prints a whole list, it shows the square brackets and the quote marks too. The word len is short for length, and len(backpack) tells you how many items are in the list. There are three.
Picking out one item
Each item has a number called its index, which tells you its place in the list. And here is the surprise: the counting starts at 0, not 1.
| Item | "torch" | "map" | "sandwich" |
|---|---|---|---|
| Index | 0 | 1 | 2 |
To get one item, write the list name and then the index in square brackets:
backpack = ["torch", "map", "sandwich"]
print(backpack[0])
print(backpack[1])
print(backpack[2])
print(backpack[-1])
torch map sandwich sandwich
The last line shows a handy trick. A negative index counts from the end, so -1 is always the last item, however long the list is.
Pixel says Think of numbered pegs on a wall. The first peg is number 0. If you have 3 items, the pegs are 0, 1 and 2. There is no peg number 3, and if you ask for it, Python shows an IndexError message. That is a bug, and now you know how to fix it. Meow!
Changing a list
Use append to add a new item to the end of the list. The word means “stick on the end”.
backpack = ["torch", "map"]
backpack.append("compass")
backpack.append("apple")
print(backpack)
print("Items:", len(backpack))
['torch', 'map', 'compass', 'apple'] Items: 4
You can swap one item for another by assigning to its index, and remove an item by name:
backpack = ["torch", "map", "sandwich"]
backpack[1] = "telescope"
backpack.remove("sandwich")
print(backpack)
['torch', 'telescope']
You can also ask whether something is in the list, using the word in. It gives you a yes or no answer, so it works perfectly with if:
backpack = ["torch", "map", "sandwich"]
if "map" in backpack:
print("Great, we will not get lost!")
else:
print("Oh no, we forgot the map!")
Great, we will not get lost!
Looping over a list
Remember from the last lesson that a for loop can walk through a list? Now you can use it on your own lists:
backpack = ["torch", "map", "sandwich", "compass"]
for item in backpack:
print("In my backpack:", item)
In my backpack: torch In my backpack: map In my backpack: sandwich In my backpack: compass
If you want a numbered list, loop over the positions with range(len(...)). The + 1 makes the numbers start from 1, which is how people usually count:
backpack = ["torch", "map", "sandwich", "compass"]
for position in range(len(backpack)):
print(position + 1, backpack[position])
1 torch 2 map 3 sandwich 4 compass
Fill the backpack with input
Lists and input work well together. This program asks for three things and packs them one by one. We start with an empty list, written [].
backpack = []
for turn in range(3):
thing = input("What will you pack? ")
backpack.append(thing)
print("Your backpack has", len(backpack), "things:")
for thing in backpack:
print("-", thing)
If you typed banana, kite and rope, the whole conversation would look like this:
What will you pack? banana What will you pack? kite What will you pack? rope Your backpack has 3 things: - banana - kite - rope
Did you know? Lists can hold numbers too, and even a mixture of things. [10, 20, 30] is a list of numbers. Python can add them up for you with sum([10, 20, 30]), which gives 60.
Challenges
Try it Make a list of your four favourite foods. Print the first one and the last one.
Show the answer
foods = ["pizza", "pancakes", "grapes", "popcorn"]
print(foods[0])
print(foods[-1])
pizza popcorn
Try it Start with pets = ["cat", "dog"]. Add a “hamster” to the end, then print how many pets there are, and loop through the list to print each one.
Show a hint
Use pets.append("hamster"). Then print len(pets), and use a for pet in pets: loop.
Show the answer
pets = ["cat", "dog"]
pets.append("hamster")
print("Number of pets:", len(pets))
for pet in pets:
print(pet)
Number of pets: 3 cat dog hamster
Try it What would print(backpack[3]) do if the backpack had only 3 items? Try it and read the message. Which index is the last one?
Show the answer
Python shows an IndexError because there is no item at index 3. A list with 3 items has indexes 0, 1 and 2, so the last one is index 2 (or -1).
What you learned
- A list holds many items in one variable. You write it with
[ ]and commas. - Each item has an index, and the first index is 0.
len(list)counts the items,appendadds one at the end, andremovetakes one out.item in listchecks whether something is there.- A
forloop can walk through every item in a list.
