Nested for Loop in Python

In this tutorial, we will discuss Nested for Loop in Python programming.

Nested Loop:

The Nested Loop is Loop that is inside another loop which is called the outer loop. There are two loops in the Nested Loop which is called the inner and outer Loop. The inner or outer loop can be any type, such as a while loop or for loop. For Example, if the outer loop is for loop can contain while or for loop or vice versa.

Nested for Loop:

In Python, for loop is used to iterate over a sequence. Nested for loop is mean by a for loop inside the for loop or while loop inside the for loop.

for loop inside the for loop in Python 

Here, we take a range of numbers to add them. The first for loop is the outer loop it iterates numbers from 1 to 5.  So the range returns 5 numbers only. Then in the outer loop 5 iterations are done. Here, a and b are two variables that are in order which means in the range of numbers, The first iteration of the Nested loop is 1 and then 2. Here addition condition is specified.

order = range(1,6)
for a in order:
    for b in order:
        print(a + b, end=' ')
    print()

Output:

2 3 4 5 6

3 4 5 6 7

4 5 6 7 8

5 6 7 8 9

6 7 8 9 10

while loop inside the for loop in Python

numbers = [1, 2, 3, 4]

for num in numbers:
    count = 0
    while count < 6:
        print(num, end= ' ')
        count = count + 1
    print()

Output:

1 1 1 1 1 1

2 2 2 2 2 2

3 3 3 3 3 3

4 4 4 4 4 4

Also read: Python Looping Techniques

Leave a Reply

Your email address will not be published. Required fields are marked *