Nested For Loop in Python

Nested For Loop

Python For Loop is just like another Python command or statement. Therefore, we can write a for loop inside another for loop and this is called nesting.

For loop inside another for loop is called Nested For Loop.

Examples

Print Triangular Pattern

In the following program, we shall write a nested for loop, to print a triangular pattern.

Python Program

n = 6

for x in range(n):
    for y in range(x+1):
        print('* ', end=' ')
    print()

Output

*  
*  *  
*  *  *  
*  *  *  *  
*  *  *  *  *  
*  *  *  *  *  *  

Iterate over List of Lists

In the following program, we shall write a nested for loop, to iterate over a List of Lists.

Python Program

input = [
            ['a', 'b', 'c'],
            ['d', 'e', 'f'],
        ]

for inner in input:
    for element in inner:
        print(element)

Output

a
b
c
d
e
f

Summary

In this tutorial of Python Examples, we learned how to write nested for loops with examples.

Code copied to clipboard successfully 👍