Making Sense of a Nested For Loop

Nested for loops can get tricky because of the different operations in each statement. They can be difficult to understand, but once you understand what is happening, it becomes evident how your computer is running the loop.

Let’s start with one for loop.

In this example, we will add numbers together. I start with my list of numbers 0, 1, 2, 3, and 4. The range function includes the first number in the argument, but the second number is excluded.

So adding these together in a loop, we get:

This makes sense because the loop starts with zero, adds it to itself, then prints the result. Zero plus zero is zero, so ‘0’ is printed. The loop then moves to the next number, 1. It adds one to one and produces ‘2.’ This process repeats for each number in the list until the last number is added to itself.

Now for our nested for loop.

Let's say we have a second list,

This second list outputs 5, 6, and 7. Let’s add each number from our first list to these numbers. The line print(‘\n’) is to print a blank new line. I'm using it to space out the numbers, but it is not necessary for the loop.

Let’s break down what the loop is doing. The first line tells us we will iterate through each integer in our number_list and assign it the variable i.

After pulling the integer, we will print a new line.

Then, print the integer.

A second_list is created, then it is printed. We see it contains the numbers 5, 6, and 7 by running the print function.

The second for loop says for each number in our second_list, it will add i to each number.

As a result, we see each number from the number_list is added to second_list. 0 + 5 = 5, 0 +6 = 6, and 0 + 7 = 7.

When reading for loops, it is good practice to take your time and understand each line before moving on. Talking it out can help, and take your time!

Data Scientist