Python Nested Loops Examples
Let's look at examples to see nested loops in action. Consider you're working on a task where you need to print a multiplication table for numbers 1 through 5. Using nested loops, you can achieve this efficiently:
Python
for i in range(1, 6): # Outer loop for each row (1 to 5)
for j in range(1, 6): # Inner loop for each column (1 to 5)
print(f"{i * j}\t", end='') # Print product and add a tab space
print() # New line after each row

You can also try this code with Online Python Compiler
Run Code
This script outputs a 5x5 grid where each cell is the product of its row and column indices:
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
Another common application of nested loops is when dealing with 2D data structures, like grids or matrices. Suppose you have a grid of colors, and you need to check each cell to see if it matches a specific color:
Python
colors = [["red", "blue", "green"], ["blue", "blue", "red"], ["green", "red", "blue"]]
search_color = "blue"
for row in colors:
for color in row:
if color == search_color:
print("Blue found!")

You can also try this code with Online Python Compiler
Run Code
Output
Blue found!
This code checks each cell in the matrix and prints "Blue found!" whenever it encounters the color blue. Nested loops make it straightforward to process each element in such structured data.
Using Break Statement in Nested Loops
The break statement in Python allows you to exit a loop when a specific condition is met. This can be particularly useful in nested loops if you want to stop an iteration prematurely once you have found what you were looking for, or if continuing would be unnecessary or inefficient.
Example
Python
numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
found = False # This flag will indicate whether the target was found
for row in numbers:
for number in row:
if number == target:
print(f"Found {target}!")
found = True
break # Exit the inner loop
if found:
break # Exit the outer loop too

You can also try this code with Online Python Compiler
Run Code
Output
Found 5!
In this example, we search for the number 5 in a 2D array. Once we find the number, we print "Found 5!" and use break to exit the inner loop. We also check if the number was found using a flag (found), and if so, we break out of the outer loop as well. This prevents the loops from executing further and saves computational resources once the target is found.
Note : This approach is very efficient when you’re dealing with large datasets and you only need to find a single occurrence of an element. Without the break statement, the loops would continue to execute unnecessarily even after the target has been found.
Using Continue Statement in Nested Loops
The continue statement in Python is used to skip the current iteration of a loop and continue with the next iteration. This is particularly useful in nested loops when you want to skip certain elements under specific conditions but still need to complete the looping process.
Let's look at an example where we use the continue statement in nested loops:
Python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
skip_value = 5
for row in matrix:
for number in row:
if number == skip_value:
continue # Skip this iteration and move to the next number
print(number, end=' ')
print() # Print a new line after completing each row

You can also try this code with Online Python Compiler
Run Code
In this code, we traverse a 2D array (or matrix) and decide to skip printing the number 5. The continue statement causes the loop to skip printing when it encounters the number 5 but continues with the next number in the row.
Output
1 2 3
4 6
7 8 9
You can see that the number 5 is not printed, but all other numbers are processed normally. This example shows how continue can be useful in managing flow control within nested loops, allowing for more complex and specific behaviors depending on your needs.
Single Line Nested Loops Using List Comprehension
Python's list comprehension feature can simplify the syntax of nested loops into a single line, making your code cleaner and more readable. This technique is especially useful when you need to create new lists based on existing lists.
Example
Python
# Example: Create a multiplication table in a single line using nested loops with list comprehension
multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
# Print the multiplication table
for row in multiplication_table:
print(row)

You can also try this code with Online Python Compiler
Run Code
This code snippet creates a 5x5 multiplication table. The outer list comprehension (for i in range(1, 6)) represents rows, and the inner list comprehension (for j in range(1, 6)) represents columns. Each element in the table is the product of the current row and column indices.
The output of this script will be:
[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]
Using list comprehension not only condenses multiple lines of loop logic into a single, understandable line but also enhances performance by being faster than equivalent nested loops written in the traditional way.
Note : This approach to writing nested loops is compact and can be particularly advantageous when dealing with more complex operations that require nested iterations but want to maintain clarity and reduce the number of lines in your code.
Time & Space Complexity of Nested Loops
Time Complexity
For nested loops, the time complexity often depends on the number of times each loop runs. If you have two nested loops, each running n times, the time complexity is O(n2). This means if the loop body takes constant time to execute, the total execution time grows quadratically with the number of iterations.
Here’s a simple way to understand this:
Python
# Count the number of iterations in a nested loop
count = 0
n = 5
for i in range(n):
for j in range(n):
count += 1
print(f"Total iterations: {count}")

You can also try this code with Online Python Compiler
Run Code
Output
Total iterations: 25
In this code, both the outer and inner loops run 5 times, resulting in a total of 5×5=25 iterations. So, the time complexity is O(n2).
Space Complexity
The space complexity for basic nested loops is generally O(1), which means it does not increase with the size of the input data. This is because there are no additional data structures taking up space proportionally to the input size. The memory used is constant as only a few variables (loop counters and temporary data) are involved.
Note : It's important to keep these complexities in mind when writing nested loops to ensure your code runs efficiently and is scalable. High complexity can lead to slow responses and can be impractical with large inputs.
Frequently Asked Questions
Can nested loops be used for tasks other than numeric calculations?
Yes, nested loops are versatile and can be used for a variety of tasks, including searching and sorting data in multi-dimensional arrays, generating patterns, and processing nested data structures like lists of lists.
Is there a limit to how many loops can be nested in Python?
Python does not have a strict limit on the depth of nested loops. However, the more loops you nest, the more complex your code becomes, which can lead to slower execution times and harder-to-maintain code.
How can I avoid performance issues with nested loops?
To avoid performance issues, consider breaking down complex tasks into simpler functions, using list comprehensions where appropriate, and ensuring that the conditions for loop termination are not too broad, thus minimizing the number of iterations.
Conclusion
In this article, we have learned the fundamentals of nested loops in Python, covering their syntax, practical examples, and control structures like break and continue. We've also explained how to implement nested loops briefly using list comprehension and discussed the implications of time and space complexity on performance.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.