Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Looping in python
  5. Nested loops in python

Nested loops in python

Python language allows use of loop inside another loop. This is called nested loop.

But in nested loop, the inner loop must terminate before the outer loop. While working with nested loops, you need to understand one thing and that is, the value of the outer loop variable will change only after the inner loop is completely finished.

syntax of a nested loop, where a for loop is nested inside another for loop:-

for variable in sequence:
    for variable1 in sequence:
         statements
    statements

syntax of a nested loop, where a while loop is nested inside another while loop:-

while expression1:
    while expression2:
         statements
    statements

e.g.,

a= ['python', 'Java', 'C++', 'JavaScript']
b = ['First', 'second', 'third']
for i in a:
  for j in b:
    print(i, j)

This is all about nested loops in python.

Was this article helpful to you? Yes No

How can we help?