Ages 10+ · Coding · Python
Lists in Python
The list • snacks = ["mango", "pear", • "plum", "fig"] The boxes • box 0: mango • box 1: pear • box 2: plum • box 3: fig Four snacks in four numbered boxes. The big idea A list keeps many things in numbered boxes, and the first box is zero.
How it works A list keeps many things under one name, in a row of numbered boxes, inside square brackets.
Python starts counting its boxes at zero, not one. The first box is box zero, no steps from the start.
Len counts the boxes. The count is one more than the last box number.
Append adds one thing at the end, and a for loop can visit every box in turn.
Make the list Add the kiwi Count the boxes Fetch the last box Mina's snack list grows. Example 1: Fetching a box The list is snacks = ["mango", "pear", "plum", "fig"]. Box zero holds the mango, box one the pear, box two the plum and box three the fig. Asking for snacks[1] means box one, so out pops the pear. Example 2: Counting the boxes The list holds four snacks. Len of snacks says four. The last box is number three, one less than the count. Example 3: Adding at the end Teo brings a kiwi, and Mina uses append. A fifth box appears at the end, and the kiwi is in box four. Len now says five, and the last box is number four. Example 4: Visiting every box A for loop visits each box in turn, from box zero. Mango, pear, plum, fig, kiwi: nobody is missed, and it takes only two lines. Even a hundred snacks would need only two lines. Words to know list Many things kept under one name, in a row of numbered boxes. box number A number that says which box to open. It counts from zero. len Counts the boxes in a list. append Adds one new box at the end of a list. for loop Repeats lines, once for every box in a list. Watch out Counting starts at zero, so the pear is in box one, not box two. Len says how many boxes there are, and the last box is one less than that. A list of four things has no box four, until append adds one. Box numbers go in square brackets, as in snacks[1]. Try it A list holds mango, pear, plum and fig. Which snack is in box two? A list has five things. What is the number of the last box? A list has seven things. What does len say? Teo uses append to add a kiwi to a list of four. Which box holds the kiwi? Which line asks for the pear in snacks: snacks[0] or snacks[1]? Answers: 1. plum · 2. 4 · 3. 7 · 4. Box four · 5. snacks[1]
Try at home With a grown-up, write four things, such as snacks, on four paper boxes, and number the boxes from zero. Ask them to say a number, and you hold up that box. Then add a fifth box at the end, just like append.
For grown-ups Do the Mission: write four things on four paper boxes, number them from zero, and ask your child to hold up the box you name. Then add a fifth box at the end, like append.