Nested loops in Python (21/100 Days of Python)
Nested loops in Python allow you to loop through multiple sequences at the same time. They are useful for iterating through multi-dimensional data structures, such as lists of lists, matrices, and other complex data structures.
A nested loop is simply a loop that is inside another loop. The inner loop will execute for each iteration of the outer loop:
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for sublist in lists:
for item in sublist:
print(item)
This code will output all the items in the list one by one — 1, 2, 3, 4, 5, 6, 7, 8, 9.
You can also use nested loops to iterate through a matrix (2D list), using indices:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i][j], end=' ')
print()
This will print a nice square matrix:
1 2 3
4 5 6
7 8 9
It’s possible to nest more than 2 loops inside each other. You can iterate over hours, minutes, and seconds of the day using 3 loops:
for h in range(24):
for m in range(60):
for s in range(60):
print(f'Time: {h}:{m}:{s}')
This program will print all possible hours, minutes, and seconds of a day starting from 0:0:0
up to 23:59:59
. Try running this program to see what it outputs.
It’s important to be careful when using nested loops, as the number of iterations can quickly become very large, especially when working with large data sets. This can lead to performance issues, such as long execution times and high memory usage.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — nested loops
- Full series: 100 Days of Python
- Previous topic: 10 most useful list methods
- Next topic: Python List Comprehension