Nested For Loop in Python
In Python, a nested for
loop is a loop inside another loop. The inner loop executes completely for each iteration of the outer loop, making it useful for working with multi-dimensional data structures such as matrices, grids, and nested lists. In this tutorial, we will explore how nested for
loops work in Python with examples.
Examples
1. Printing a Pattern using Nested For Loops
Nested loops can be used to generate patterns, such as a right-angled triangle made of stars.
# Number of rows
rows = 5
# Outer loop for rows
for i in range(1, rows + 1):
# Inner loop for columns
for j in range(i):
print("*", end=" ")
print() # Move to the next line
Explanation:
- The outer loop (
for i in range(1, rows + 1)
) iterates over the rows. - The inner loop (
for j in range(i)
) runsi
times in each iteration of the outer loop, printing*
. - The
print()
at the end moves the cursor to a new line after each row.
Output:
*
* *
* * *
* * * *
* * * * *
2. Iterating Over a 2D List (Matrix)
We can use nested loops to iterate through a two-dimensional list (a matrix).
# Defining a 2D list (Matrix)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Iterating over the rows
for row in matrix:
# Iterating over the elements in each row
for element in row:
print(element, end=" ")
print() # Move to the next line
Explanation:
- The outer loop (
for row in matrix
) iterates over each list (row) in the matrix. - The inner loop (
for element in row
) iterates over elements in each row. print(element, end=" ")
prints elements in a single row, andprint()
moves to the next line.
Output:
1 2 3
4 5 6
7 8 9
3. Generating Multiplication Table
Nested loops can be used to generate a multiplication table.
# Multiplication table up to 5
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:2}", end=" ")
print() # Move to the next line
Explanation:
- The outer loop (
for i in range(1, 6)
) controls the row numbers (multiplicands). - The inner loop (
for j in range(1, 6)
) iterates through multipliers. i * j
calculates the product and prints it in a formatted way.
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
4. Finding Prime Numbers in a Range
We can use nested loops to check if numbers in a range are prime.
# Find prime numbers from 2 to 20
for num in range(2, 21):
is_prime = True
for div in range(2, int(num ** 0.5) + 1):
if num % div == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Explanation:
- The outer loop (
for num in range(2, 21)
) iterates through numbers from 2 to 20. - The inner loop (
for div in range(2, int(num ** 0.5) + 1)
) checks ifnum
is divisible by any number between 2 and its square root. - If a divisor is found,
is_prime
is set toFalse
, and we exit the loop. - If no divisor is found, the number is prime and printed.
Output:
2 3 5 7 11 13 17 19
Conclusion
Nested for
loops in Python are useful for iterating over multi-dimensional data and performing operations like pattern printing, working with matrices, generating multiplication tables, and more. Here are the key takeaways:
- The outer loop runs first, and the inner loop completes its execution for each iteration of the outer loop.
- They are useful in handling 2D lists, matrices, and structured data.
- Breaking out of the inner loop does not affect the outer loop.