In Python, you can simply use a loop inside the loop to get double loops. In Double-loop The “inner loop” will be executed one time for each iteration of the “outer loop”.
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
Python Double for loop example
Simple example code
num = [1, 2, 3] fruits = ["Apple", "Banana"] for x in num: for y in fruits: print(x, y)
How to exit a double loop in python?
Answer: Use the break keyword to break the double loop. When the break is executed in the inner loop, it only exits from the inner loop and the outer loop still continues.
l1 = [1, 2, 3] l2 = [10, 20] for i in l1: for j in l2: print(i, j) if i == 2 and j == 20: print('BREAK') break
Breaking out of two loops example
for i in range(1, 3): for j in range(1, 5): print(i, j) if i == j: print("Break All loops") break else: continue break
Break All loops
Do comment if you have any doubts and suggestions on this Python loop topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.