When you define the one loop inside the other loop is called a Nested loop in Python. The “inner loop” will be executed one time for each iteration of the “outer loop”:
Note: The outer loop can contain any number of the inner loop. There is no limitation on the nesting of loops.
Python nested loop example
Simple example codes each iteration of an outer loop the inner loop re-start and completes its execution before the outer loop can continue to its next iteration.
color = ["Red", "Green", "Black"] num = [1, 2, 3] for x in color: for y in num: print(x, y)
Nested 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('')
* * * * * * * * * * * * * * *
Break Nested loop
Use the break statement inside the loop to exit out of the loop. If the break statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.
for i in range(4): for j in range(4): if j == i: break print(i, j)
Continue Nested loop
for i in range(2): for j in range(2): if j == i: print("Skip") continue print(i, j)
How to Single Line Nested Loops?
Answer: Using List Comprehension get all combinations of 2 lists.
first = [2, 3, 4] second = [1, 0, 5] final = [i + j for i in first for j in second] print(final)
Output: [3, 2, 7, 4, 3, 8, 5, 4, 9]
Please comment if you have any doubts or suggestions on this Python loop topic.
Note: IDE: PyCharm 2021.3.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.