In this lesson we will learn how to use nested loops in Python, that is, iterations that run inside other iterations.

So, let’s take some examples to understand how they work.

Example on nested loops in Python

Produce a rectangle of asterisks of base 4 asterisks and height 3.

The output must therefore be this:

* * * *
* * * *
* * * *

To accomplish this we use two loops, one external and one internal.

Two nested for loops require different counters, we denote with i the counter of the first loop, while with j the counter of the second loop.

Banner Pubblicitario

So, in this case, the external cycle will be repeated three times, while the internal one four times for each external cycle.

Here is the complete code:


for i in range(3):
    for j in range(4):
        print('*', end=' ')
    print()

We use the keyword end inside the print to insert the asterisks on the same line and therefore avoid going to the head.

While the last print() is simply used to wrap, after printing each line.

So let’s explain step by step what happens.

  1. First iteration of the outer loop: i = 0
  • First iteration of the inner loop: j = 0 prints the asterisk followed by the empty space.
  • Second iteration of the inner loop: j = 1 prints another asterisk followed by white space.
  • Third iteration of the inner loop: j = 2 prints an asterisk followed by white space.
  • Fourth iteration of the inner loop: j = 3 prints an asterisk followed by white space.

2. Second iteration of the outer loop: i = 1

We proceed similarly to what was said before.

Banner pubblicitario

To test what explained, try replacing the asterisks for the values of i and j, inserting the code indicated below instead of print (‘*’, end = ”):


print('i:',i,'j:',j, end=' ')

The same rectangle could be made with a single for loop, simply by multiplying the asterisk (*) character 4 times for each line.


for i in range(3):
    print('* '*4)

Second example on nested loops in Python

We vary the previous exercise by now producing a rectangle with the numbers from 1 to 4.

That is, the output must be this:

1 2 3 4 1 2 3 4 1 2 3 4

We only have to change the inner loop, setting the values (1,5) in the range.

After, at each iteration of the internal cycle we print the index j.

So here’s the code:


for i in range(3):
    for j in range(1,5):
        print(j, end=' ')
    print()

Third example on nested loops in Python

Print the numbers in descending order, then we run the previous example in order to have the following output:

4 3 2 1 4 3 2 1 4 3 2 1

To print the numbers in descending order we can change the range so that j varies from 4 to 1 with steps of -1.

Here is the complete code:


for i in range(3):
    for j in range(4,0,-1):
        print(j, end=' ')
    print()

Fourth example

We now want to create another example using two nested for loops, like the example below:

1234567 123456 12345 1234 123 12 1

Just print j and from time to time decrease the number of lines by 1:


n=7
for i in range(n):
    for j in range(1, n+1-i):
        print(j, end='')
    print()

Fifth example on nested loops in Python

Let’s take another example:

7654321 654321 54321 4321 321 21 1

n=7
for i in range(n):
    for j in range(n-i,0, -1):
        print(j, end='')
    print()

Sixth example

Let’s take another example on nested loops:

1 21 321 4321 54321 654321 7654321

n=7
for i in range(1,n+1):
    for j in range(i,0, -1):
        print(j, end='')
    print()

Seventh example on nested loops in Python

Let’s make a figure like this:

* ** *** **** ***** **** *** ** *

Let’s analyze some solutions. First solution:


n=5
for i in range(1,n*2):
    if i<=n:
        for j in range(i,0, -1):
            print('*', end='')
    else:
         for j in range(1,n*2+1-i):
            print('*', end='')
        
    print()

The outer loop will print the nine lines. In fact i varies from 1 to 9.

Within the cycle, if i <= 5, we perform another for cycle which will print 1 asterisk the first time, then 2, etc … up to 5.

In fact, at the first iteration i is equal to 1, at the next it is 2 and so on up to i = 5.


for j in range(i,0, -1):
    print('*', end='')

When i is equal to 5, what is written in the else will be done and then the other for loop which will print n * 2-i asterisks. The first time n * 2-i = 10-6 that is 4 asterisks, the second time n * 2-i = 10-7 that is 3 and so on.

Second simplified solution with two for loops:


n=5
for i in range(1,n*2):
        for j in range(1,n+1):
            if i<=n and j<=i:
                print('*', end='')
            elif i>n and j

Third solution with logical operators:


n=5
for i in range(1,n*2):
        for j in range(1,n+1):
            if i<=n and j<=i or i>n and j

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot