Python nested for | Example code

The for loop is used to iterate over a sequence such as a list, string, tuple, other iterable objects such as range. Using a for loop inside a for a loop is called a Python nested for.

for x in sequence:

  for y in sequence:

The outer loop can contain more than one inner loop without limitation on the chaining of loops.

Python nested for example

Simple example code for Nested loop to print multiplication table in Python

for i in range(0, 5):

    for j in range(0, 5):
        print(i * j, end=' ')
    print()

Output:

Python nested for

Another example

Nested for Loop to Print Pattern.

rows = 5
# outer loop
for i in range(1, rows + 1):
    # inner loop
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')

Output:

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

Do comment if you have any doubts and suggestions son this Python nested topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.