TwiddleLab / Code / How a Programmer Thinks
Lists: Many Boxes in a Row
What you will learn
- A list holds many values in order under one name: scores = [72, 45, 90].
- Each value has an index starting at 0: scores[0] is the first, scores[1] the second.
- len(scores) says how many there are, so the last one is scores[len(scores) - 1].
- append adds a value at the end. An index past the end gives an IndexError.
How the lesson goes
Your game keeps your last scores. Save them.
Drag each score into its own box.
Open scores[1].
Which locker does scores[1] open? Tap it.
Run a loop over the list.
Press Step. Watch the lockers open one by one, then watch the list grow.
Lists have their own words.
A list keeps many values in order, in square brackets, under one name.
Each spot has an index, starting at 0. scores[0] is 72, the first one.
append adds to the end. len counts the values: here 3, then 4.
Ask for an index that isn't there, like scores[9], and Python stops with an IndexError. Now watch this code run.
Find the best score.
The pointer visits each locker once. Keep it as best, or skip it. No mistakes for three stars.
Make a list of the scores above 50.
Put the lines in order and Run. One line is a trap.
Your screen time this week, as a list.
Drag roughly how many hours you spent on screens each day. Math's average is a loop plus len.
This should print the last score. It crashes.
Run it, read the message, fix the index.
Which locker does this open?
Tap it.
Speed round on your own week.
Where does each one land: the first day, the last day, or a crash?
Previous lesson: Loops: Do It Again · Next lesson: Sorting, One Swap at a Time · Part of the course: How a Programmer Thinks
Lessons are interactive and need JavaScript. Turn it on to play them.