Tutorialspoint

How to use nested loops in Python?

How to use nested loops in Python?                                                


1 Answer
Malhar Lathkar
, 1 Views

In programming, the term nesting is used when a construct is used inside another construct of same type. Hence nested loop refers to use of a loop inside a loop. In such a case inner loop takes all iterations for each iteration of outer loop.

In Python the body of loop is group of statements with an increased indent level. In case of nested loop, indent level of inner loop id more than outer loop. Following simple example of nested loop shows the feature:

for x in range(4):
    for y in range(4):
        print (x,y)

This produces following output

0 0
0 1
0 2
0 3

1 0
1 1
1 2
1 3

2 0
2 1
2 2
2 3

3 0
3 1
3 2
3 3
Advertisements