Table of Contents
ToggleIn Python, nested loops are used when you write one or more loops inside another loop. The outer loop is the main loop, and the inner loop(s) are executed repeatedly for each iteration of the outer loop. This guide will explain how to use nested loops in Python with examples.
Nested loops are loops within loops. You can use any type of loop inside another loop, such as a for loop inside a while loop or vice versa. Nested loops are commonly used for iterating over multi-dimensional data structures like lists of lists or matrices.
A for loop inside another for loop is called a nested for loop. It is used to iterate over sequences like lists, tuples, or strings.
months = ["jan", "feb", "mar"]
days = ["sun", "mon", "tue"]
for x in months:
for y in days:
print(x, y)
print("Good bye!")
Output:
jan sun
jan mon
jan tue
feb sun
feb mon
feb tue
mar sun
mar mon
mar tue
Good bye!
A while loop inside another while loop is called a nested while loop. It is used to repeat a block of code until a condition is met.
i = 2
while(i < 25):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j): print(i, "is prime")
i = i + 1
print("Good bye!")
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
Good bye!
Nested loops are a powerful feature in Python that allow you to handle complex iterations efficiently. Whether you’re working with for loops or while loops, understanding nested loops is essential for solving advanced programming problems.
