In one of my previous articles we were talking about nested lists and dictionaries. Today we’ll be talking about nested loops.
Loops can be nested. Here’s an example of a nested for loop:
for row in range(1, 5):
for column in range(1, 4):
print(" ({},{}) ".format(row, column), end = "")
if column == 3:
print("\n")
Here we have an outer loop with the variable row and an inner loop with the variable column. The ranges contain numbers 1-4 and 1-3 respectively, which means the outer loop will run 4 times, creating 4 rows and in each iteration of the outer loop, the inner loop will run 3 times, creating 3 columns. Then a formatted string is printed in the form: (row, column), surrounded by spaces on both sides. Each line will end in an empty string, thus not jumping to a new line. Only every third time will it jump to a new line, so if column is 3. That’s what we want for a nicer layout. So, if column equals 3, a newline character is printed, which does the work.
If you want to read more about the end parameter in the print function that I used in the code above to prevent it from jumping to a new line, here’s an article about it: How to Use the end Parameter in the print Function.
Here’s how the loops will work:
So, here’s the output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
(4,1) (4,2) (4,3)
Nesting Everywhere
Nesting is a pretty common phenomenon in Python, as well as other programming languages. You can nest loops, lists, dictionaries or functions, to mention just a few. I also have some other articles where this topic is covered.
In my article The break Statement in Python we’re talking about the break
statement used in a nested loop, so this may interest you as well. There’s also the slightly more advanced article Save Loop Variable’s Value in Functions Nested in Loops where we talk about functions nested in loops.