Loops, and where your data lives

INPUT · Slides

A loop inside a loop

01 / 07

A loop inside a loop

What you can write inside a for is not limited to print and sums. A for itself goes in there too.

This is called nesting. A times table, a grid, the combinations of two things — anything with rows and columns is usually built this way.

02 / 07

The shape and the movement

The inner for is written four spaces deeper again, just as it was when you nested an if.

Follow the example below with your eye. While i is 0, j runs all the way through 0, 1, 2. Then i becomes 1 and j starts again from 0.

for i in range(2):    for j in range(3):        print(i, j)

Result

0 0
0 1
0 2
1 0
1 1
1 2

03 / 07

The goes multiply

Here is the important part. In the time the outer one moves on once, the inner one goes all the way round.

Two outside and three inside means the innermost line runs 2 * 3, that is six times. The goes multiply — learn it that way.

Ten outside and ten inside is a hundred. Nesting makes the count swell alarmingly, so mind how much you put on the screen.

04 / 07

Building a times table

The classic rows and columns is a multiplication table. The outer loop takes the row, the inner one takes what to multiply by.

Here are only the two and three times tables. The point is that the row is chosen by range(2, 4).

for i in range(2, 4):    for j in range(1, 4):        print(f"{i} times {j} is {i * j}")

Result

2 times 1 is 2
2 times 2 is 4
2 times 3 is 6
3 times 1 is 3
3 times 2 is 6
3 times 3 is 9

05 / 07

Building a grid

Assemble one line of text in the inner loop and show it in the outer one. That shape builds a rectangular grid.

The thing to notice is that line is emptied inside the outer loop. Take that out of the loop and the text from the previous row stays put and simply keeps growing.

for row in range(3):    line = ""    for column in range(4):        line += "■"    print(line)

Result

■■■■
■■■■
■■■■

06 / 07

Combining two lists

What follows in does not have to be a range. Combine one list with another and you can turn out every pattern there is.

Two colours and two sizes make four combinations. Here too, the goes multiply.

for colour in ["red", "blue"]:    for size in ["S", "M"]:        print(colour, size)

Result

red S
red M
blue S
blue M

07 / 07

Do not go too deep

You can nest three deep, or four. But the deeper it goes the less readable it is, and the count swells with it.

Two levels is the guide. Wanting a third is usually a sign that there is another way to write it. Functions and the list tools will give you more of those.

That is the set of tools for repeating. In the next group we look at handling lists far more freely.