Two for loops in Python | Example code

Their many ways used to Two for loops in Python. Like combine 2 lists or addition or filter out by conditions or print any pattern.

Example 1

Multiplication of numbers using 2 loops.

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

Output:

Two for loops in Python
Two for loops in Python

Example 2

Nested while loop Python.

i = 1
j = 5

while i < 4:
    while j < 8:
        print(i, ",", j)

        j = j + 1
        i = i + 1

Output:

1 , 5
2 , 6
3 , 7

Example 3

Nested for loop example

color = ["Red", "Green"]
num = [1, 2, 3]

for x in color:
    for y in num:
        print(x, y)

Output:

Red 1
Red 2
Red 3
Green 1
Green 2
Green 3

How to break out of two for loops in Python?

breaker = False
i = 1
while True:
    while True:
        print(i)
        if i == 0:
            print("Zero")
            breaker = True
            break
        i = i - 1
    if breaker:  # the interesting part!
        break  # <--- !

Output:

1
0
Zero

Python combine two for loops

Use itertools.product

import itertools

for x, y in itertools.product([1, 2], ['A', 'B']):
    print(x, y)

Output:

1 A
1 B
2 A
2 B

Do comment if you have any doubts and suggestions on this Python loop 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.