At sports day, how do you pull up the right sprint time as soon as someone asks?
At your school sports day, two runners each have four sprint times. Someone asks for the second runner’s third time. How could you tell a program exactly which time to find, without searching through them all?
Start with one runner’s times: fourteen, thirteen, fifteen and twelve seconds. You already use one index to pick a value from a list. In Python, counting starts at zero, so index two picks the third time, fifteen seconds.
Each runner has a row and each attempt has a column. Follow blue along row one, then green down column two. They meet at sixteen seconds. This is a two-dimensional array. In Python, write times, then one in square brackets, then two in square brackets.
The first index picks the runner and the second picks the attempt. You need the first runner’s fourth attempt. Since both indices start at zero, which line of Python picks that time? Choose one.
Store both rows in times. The outer loop uses the length of times to pick each runner index. The inner loop uses the length of that runner’s row to pick each attempt index. The print line runs for each pair. A loop inside another loop is called a nested loop.
The outer loop starts with runner zero. The inner loop prints fourteen, thirteen, fifteen and twelve, in that order. Then the outer loop moves to runner one. The inner loop starts from the first attempt again and prints eighteen, seventeen, sixteen and nineteen. That’s eight times printed.
Now there are three runners with two attempts each. The first row holds ten and eleven, the second holds twelve and thirteen, and the third holds fourteen and fifteen. With the same runner-first loops, which sequence gets printed? Pick one.
In the original array, swapping one and two makes Python look for runner index two, a third row that doesn’t exist. Keep the runner index first. Using two as the bound for both loops also misses times. Here the outer loop needs two rows, and the inner loop needs four attempts per row.
If you also need a runner’s name, you can use a record to group their details in named fields. A Python dictionary can act as a record. This one stores Sam’s name and list of times. Select the times field, then index two, to print sixteen seconds.