Copyright

Nested Loops in Python: Definition & Examples

Instructor: Paulo Lemelle Fernandes

Paulo has been a Computer Science Professor and researcher for more than 25 years. He has a Ph.D. degree from Institut National Polytechnique de Grenoble, France (1998).

In Python and many other programming languages, loops are the basic structures to perform iterations, i.e., to repeat the execution of a portion of code several times. However, sometimes you need to put one loop inside another, i.e., you need to nest the loops. In this lesson, we will see how to deal with the nested loops in Python and the precautions you need to take to use the break and continue commands within nested loops.

Basics of Loops in Python

The focus of this lesson is nested loops in Python. We will exemplify the simple case of one loop inside another, but everything works just the same way when you have more than two nested loops, being the for loop or the while loop.

However, let us review the following basic concepts about loops in Python:

  • There are two basic forms to do loops in Python. Although you can do basically the same with both of them, usually they are used for:
    • iterations that you know how many times they will occur (even if you can stop it before) - those are the for loops.
    • iterations that you will observe something else to decide when to stop an iteration - those are the while loops.
  • The for loops start with the reserved word for followed by a variable, the reserved word in, and the specification of a range. Then, basically, the for loop will execute its commands inside the loop sequentially with the variable assuming all values inside the range.
  • The while loops start with the reserved word while followed by a condition. Then, if the condition is true, the while loop will execute its commands inside sequentially until the condition becomes false (remember that the condition is only tested at the beginning of each iteration).
  • The commands inside a loop, i.e., the commands that will be executed during each loop iteration, are defined in Python by the indentation (number of tabs before the command).
  • You can immediately terminate a loop by using the command break in the commands inside the loop. Usually, such a command is to be used after testing a condition (frequently, but not always, with an if command). This is a rarely used in a for loop, but it is used frequently in a while loop.
  • You can terminate a single iteration using the command continue that is similar to the break command. However, the break command terminates the iteration and also the loop itself. The continue command terminates the iteration, but the loop continues running with the next iteration to be executed.

Nesting a Loop

As simple as it seems, nesting a loop means simply having a loop (let's call it outer loop) that has inside its commands another loop (let's call it inner loop). For example, the code below shows two nested loops, an outer for loop over the values of i and an inner for loop over the values of j to multiply inside the inner loop all nine elements of a 3x3 matrix A by a factor f that changes according to the outer loop iteration.

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
f = 1
print(A)
for i in range(0, 3):
    f *= 10
    for j in range(0, 3):
       A[i][j] *= f
print(A)

The output of such program will be:

 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
 [[10, 20, 30], [400, 500, 600], [7000, 8000, 9000]] 

Therefore, the outer loop executes 3 iterations (i equal to 0, 1, and 2), and at each iteration it is executed:

  • the multiplication of the factor f by 10.
  • the execution of the inner loop that has 3 iterations (j equal to 0, 1, and 2), and at each iteration the element i,j of A is multiplied by f.

Using the break Command in the Inner Loop

Let's now see how the break command works in the nested loops in the following example, which has a break command inside the inner loop.

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
f = 1
print(A)
for i in range(0, 3):
    f *= 10
    for j in range(0, 3):
       A[i][j] *= f
       if A[i][j] >= 400
          break
print(A)

The output of such program will be:

 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
 [[11, 21, 31], [400, 5, 6], [7000, 8, 9]] 

In this example, the break command only happens after the if test inside the inner loop when the matrix element becomes greater or equal to 400. This happens for the element:

  • i=1 and j=0, i.e., at the second iteration of the outer loop (i=1) and the first iteration of the inner loop (j=0). The break command interrupts the inner loop at j=0 and j will not become j=1, nor j=2. However, the outer loop is not affected by the break command execution and it will go on to the next iteration with i=2.
  • i=2 and j=0, i.e., at the beginning of the third iteration of the outer loop. Note that the third iteration of the outer loop will begin normally multiplying f by 10 (becoming f=1000) and starting the inner loop again with j=0. However, the if test for the element i=2 and j=0 will be true (7000 is bigger than 400), the break command will interrupt the inner loop again, and the outer loop will end normally.

Using the break Command in the Outer Loop

Let's now see how the break command works inside the outer loop, but outside the inner loop, in the following example:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
f = 1
print(A)
for i in range(0, 3):
    f *= 10
    for j in range(0, 3):
       A[i][j] *= f
    if A[i][j] >= 400
       break
print(A)

The output of such program will be:

 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
 [[10, 20, 31], [400, 500, 600], [7, 8, 9]] 

In this example, the if test will be executed after each normal ending of the inner loop.

  • i=0 and j=2 - At the first iteration of the outer loop (i=0) and after the first complete execution of the inner loop, the value of element i=0 and j=2 will be tested (30 >= 400) and the else statement will be executed (the element value will become 31).
  • i=1 and j=2 - At the second iteration of the outer loop (i=1) the values 400, 500 and 600 are already stored, and the if test will result true (600 >= 400). Therefore, the break command will be executed interrupting the outer loop that, in consequence, will never assume the value i=2. Thus not changing the value of the i=2 elements (remaining 7, 8, and 9).

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 160 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create An Account
Support