Nested Loops

Let's learn about nested loops with an example.


Using one loop inside another loop is called nested loops in any programming language.

Syntax of a nested for loop in Python:

for i in range(n):
    for j in range(n):
        statement to iterate

Syntax of a nested while loop in Python:

while condition:
    while condition:
        statement to iterate


Let us take the simple example of printing the following pattern using Python:

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

In order to print this pattern, we first need to understand that this pattern has 5 numbers and 5 rows to print, so we have to nest two loops, like in the following code sample.

Python code

Get hands-on with 1200+ tech skills courses.