View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Nested for loop in Python

Updated on 23/01/20256,846 Views

In Python, a nested for loop means putting one for loop inside another. This lets you repeat a block of code multiple times, especially useful for working with things like tables or grids. Nested loops in python are a key concept for handling iterative tasks.

This tutorial will teach you everything about nested for loops in Python, with clear explanations and practical nested for loop in python examples. 

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

Python Nested Loops Examples  

This nested for loop in python example will illustrate the key concepts clearly. 

Consider the task of printing a multiplication table. Nested loops are perfectly suited for this. 

for i in range(1, 4):  # Outer loop: iterates from 1 to 3 (inclusive) 
    for j in range(1, 4):  # Inner loop: iterates from 1 to 3 (inclusive) for each value of i  
        product = i * j  # Calculate the product of i and j 
        print(f"{i} * {j} = {product}", end="\t") # Print the multiplication expression and result 
    print()  # Print a newline character after each row is complete

Output:

1 * 1 = 1      1 * 2 = 2      1 * 3 = 32 * 1 = 2      2 * 2 = 4      2 * 3 = 63 * 1 = 3      3 * 2 = 6      3 * 3 = 9

Explanation:

  • The outer loop (for i in range(1, 4)) iterates three times, with i taking values 1, 2, and 3. You can think of this as representing the rows of our multiplication table.
  • For each value of i, the inner loop (for j in range(1, 4)) also iterates three times, with j taking values 1, 2, and 3. This represents the columns of the table.
  • Inside the inner loop, product = i * j calculates the product of the current row number (i) and column number (j).
  • print(f"{i} * {j} = {product}", end="\t") prints the multiplication expression and its result. The end="\t" adds a tab character after each output, creating neat spacing between the columns.
  • print() after the inner loop completes prints a newline character, moving the output to the next line to start a new row.

Printing Patterns Using Different Inner and Outer Loop Ranges

This nested for loop in python example shows how different ranges affect the output.

Let's create a right-angled triangle pattern: 

rows = 5 # Define the number of rows for the pattern   
for i in range(rows): # Outer loop: iterates through each row
    for j in range(i + 1): # Inner loop: iterates from from 0 to the current row number
        print("*", end=" ") # Print an asterisk and a space  
    print() # Print a newline after each row

Output:

** ** * ** * * ** * * * *

Explanation:

  • The outer loop (for i in range(rows)) iterates rows (5 in this case) times. This controls the number of rows in the pattern.
  • The inner loop (for j in range(i + 1)) iterates from 0 to i. This is the key to creating the triangular shape. In the first row (i is 0), the inner loop runs once. In the second row (i is 1), the inner loop runs twice, and so on.
  • print("*", end=" ") prints an asterisk followed by a space. The end=" " prevents the print() function from adding a newline character, keeping the asterisks on the same line.
  • print() after the inner loop adds a newline character, moving the output to the next line to start a new row.

Printing a Multiplication Table Using Python Nested For Loops

Printing a multiplication table is a classic example that clearly demonstrates the use of nested loops in Python.  

Let's generate a multiplication table up to a specified size: 

size = 10  # Set the size of the table 
print("Multiplication Table:") # Print the table header 
# Print the header row
print("   |", end="") # Print a separator for the header row
for i in range(1, size + 1): # Iterate through the numbers for the header row
    print(f"{i:3}", end="") # Print the number with width 3 for alignment
print() # Print a new line 
print("-" * (4 * size + 3)) # Print a separator line 
for i in range(1, size + 1): # Outer loop: iterates through rows  
    print(f"{i:2} |", end="")  # Print the row header with a separator 
    for j in range(1, size + 1): # Inner loop: iterates through columns  
        product = i * j  # Calculate the product # Calculate the product
        print(f"{product:3}", end="") # Print the product with width 3 for alignment 
    print()  # Print a newline after each row # Move to the next line

Output:

Multiplication Table:   |  1  2  3  4  5--------------------- 1 |  1  2  3  4  5 2 |  2  4  6  8 10 3 |  3  6  9 12 15 4 |  4  8 12 16 20 5 |  5 10 15 20 25

Explanation:

  • size = 10 defines the size of the table (up to 10x10).
  • The code first prints a header row with the numbers 1 to size.
  • A separator line is printed using string multiplication.
  • The outer loop (for i in range(1, size + 1)) iterates through the rows of the table.
  • print(f"{i:2} |", end="") prints the row number with a width of 2 and a vertical bar separator.
  • The inner loop (for j in range(1, size + 1)) iterates through the columns.
  • product = i * j calculates the multiplication result.
  • print(f"{product:3}", end="") prints the result with a width of 3 using an f-string for formatting, ensuring proper alignment of the numbers in the table.
  • print() after the inner loop moves the output to the next line for the next row.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

Using break Statements in Nested Loops

A break statement only terminates the innermost loop in which it is placed. The outer loop continues to execute.

Let's illustrate this with an example where we search for a specific value in a 2D list and stop the search once the value is found: 

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
] # Create a 3x3 matrix
target = 5 # Set the value to find
found = False  # Initialize a flag
for i in range(len(matrix)): # Outer loop: iterates through rows 
    for j in range(len(matrix[i])):  # Inner loop: iterates through elements in the current row  
        if matrix[i][j] == target:  # Check if the target is found
            found = True  # Set the flag
            print(f"Found {target} at row {i}, column {j}") # Print the position
            break # Exit the inner loop once the target is found # Exit the inner loop
    if found: # Check if the target was found
        break  # Exit the outer loop
if not found: # If the target wasn't found after checking all the elements
    print(f"{target} not found in the matrix") # Print a message indicating that the target is not found

Output:

Found 5 at row 1, column 1

Explanation:

  • The outer loop iterates through the rows of the matrix.
  • The inner loop iterates through the elements of the current row.
  • if matrix[i][j] == target: checks if the current element is equal to the target value.
  • If the target is found, found is set to True, a message is printed indicating the position, and the break statement is executed.
  • Crucially, the break statement only exits the inner loop. The outer loop continues its execution.
  • The if found: after the inner loop checks if the target was found in the inner loop. If it was, a second break is executed to exit the outer loop as well. This is important to stop the entire search once the target is found, making the code more efficient.
  • If the target is not found after iterating through the entire matrix, the final if not found condition is met, and a message is printed to notify the user.

Let's consider another scenario where we want to find the first row that contains a specific number: 

matrix = [
    [1, 2, 3],
    [4, 7, 6],
    [7, 8, 9]
] # create matrix
target = 7 # set the target
for i in range(len(matrix)): # loop through rows
    for j in range(len(matrix[i])): # loop through elements in the row
        if matrix[i][j] == target: # check if element is equal to target
            print(f"Found {target} in row {i}") # print row index
            break # break inner loop
    else: # This else belongs to the outer loop
        continue # Only continue if inner loop did NOT break
    break # break outer loop

Output

Found 7 in row 1

Explanation:

  • The else block is executed only if the loop completes normally (i.e., it is not terminated by a break statement).
  • If the target is found in a row, the inner loop breaks. The else block associated with the inner loop is not executed. The outer loop then also breaks because of the break statement immediately following the inner loop.
  • If the target is not found in a row, the inner loop completes normally. The else block associated with the inner loop is executed, which contains a continue statement. This continue statement does nothing in this specific context because the inner loop has already completed. It's there to clarify that the outer loop should continue only if the inner loop did not encounter the target.
  • This structure allows you to efficiently search for a value and stop the search as soon as the value is found.

Using continue Statement in Nested Loops

When continue is executed in the inner loop, the remaining statements in that inner loop's current iteration are skipped, and the inner loop proceeds to its next iteration. The outer loop is unaffected.

Let's consider an example where we want to print pairs of numbers, but skip pairs where the second number is greater than the first: 

for i in range(1, 5): # Outer loop: iterates from 1 to 4  
    for j in range(1, 5): # Inner loop: iterates from 1 to 4 for each i  
        if j > i: # Check if j is greater than i # Check if inner loop variable is greater than outer loop variable
            continue # Skip the rest of the inner loop iteration if j > i # Skip to the next inner loop iteration
        print(f"({i}, {j})", end=" ") # Print the pair
    print() # Move to the next line

Output:

(1, 1)(2, 1) (2, 2)(3, 1) (3, 2) (3, 3)(4, 1) (4, 2) (4, 3) (4, 4)

Explanation:

  • The outer loop iterates through numbers from 1 to 4.
  • The inner loop also iterates through numbers from 1 to 4 for each value of the outer loop variable i.
  • if j > i: checks if the inner loop variable j is greater than the outer loop variable i.
  • If j > i, the continue statement is executed. This skips the print(f"({i}, {j})", end=" ") statement for that specific iteration of the inner loop. The inner loop then immediately proceeds to the next value of j.
  • If j is not greater than i, the pair (i, j) is printed.

Also Read: Python Break, Continue & Pass Statements [With Examples]

Single-Line Nested Loops Using List Comprehension

List comprehensions in Python provide a concise way to create lists. They can also be used to simulate nested loops in a single line, offering a more compact syntax for certain operations. 

This nested for loop in python example shows how to use list comprehensions to achieve the effect of nested loops.

The general syntax for a nested list comprehension is: 

[expression for outer_loop_variable in outer_sequence for inner_loop_variable in inner_sequence]

Let's start by creating a matrix (a list of lists) using a nested list comprehension:

rows = 3 # Set number of rows
cols = 4 # Set number of columns
matrix = [[0 for j in range(cols)] for i in range(rows)] # Create a 3x4 matrix filled with zeros
print(matrix) # Print the matrix

Output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Explanation:

  • The outer loop for i in range(rows) iterates three times (for each row).
  • For each iteration of the outer loop, the inner loop for j in range(cols) iterates four times (for each column).
  • [0 for j in range(cols)] creates a list of four zeros. This list is then created three times by the outer loop, resulting in a 3x4 matrix.

Let's look at another example where we create coordinate pairs:

coordinates = [(x, y) for x in range(1, 4) for y in range(1, 4)] # Create coordinate pairs (x, y) where x and y are from 1 to 3
print(coordinates) # Print the coordinates

Output:

[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Explanation:

  • The outer loop for x in range(1, 4) iterates through x-values from 1 to 3.
  • The inner loop for y in range(1, 4) iterates through y-values from 1 to 3 for each x-value.
  • (x, y) creates a tuple representing the coordinate pair.

Now, let's combine this with a conditional check, similar to using continue in a traditional nested loop. 

We'll create coordinate pairs, but exclude cases where x equals y:

coordinates_filtered = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y] # Create pairs where x is not equal to y
print(coordinates_filtered) # print the filtered coordinates

Output:

[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

Explanation:

  • The added if x != y condition filters the pairs, only including those where x and y are different. This effectively replicates the behavior of continue within a nested loop.

FAQs

1. What is a nested for loop in Python?

A. A nested for loop in Python is a for loop placed inside another for loop. It allows you to execute a block of code multiple times, especially useful for iterating over multi-dimensional data.

2. When should I use nested loops in Python?

A. You should use nested loops in Python when you need to iterate over items within items, such as rows and columns in a table, elements in a matrix, or characters in a list of strings. These nested loops in python examples are common.

3. How do nested loops in Python work?

A. The outer loop executes first. For each iteration of the outer loop, the inner loop completes all its iterations. This is a crucial aspect of how nested loops in python function.

4. What is a practical nested for loop in python example?

A. Printing a multiplication table is a classic nested for loop in python example. The outer loop handles rows, and the inner loop handles columns.

5. How does the break statement work in nested loops?

A. The break statement only terminates the innermost loop in which it is placed. The outer loop continues to execute unless there is a break statement outside the inner loop as well.

6. How does the continue statement work in nested loops?

A. The continue statement skips the rest of the current iteration of the innermost loop and proceeds to the next iteration of that inner loop. The outer loop is unaffected.

7. Can I use different ranges for the inner and outer loops?

A. Yes, you can use different ranges. This allows you to create various patterns and control the iterations of each loop independently as shown in many nested loops in python examples.

8. Can I use while loops inside for loops or vice versa?

A. Yes, you can nest while loops inside for loops and for loops inside while loops. The same principles of execution apply.

9. How can I create nested lists using list comprehensions?

A. You can use nested list comprehensions, where one list comprehension is nested inside another. This provides a concise way to create multi-dimensional lists.

10. How can I use list comprehensions to simulate nested loops with conditional logic?

A. You can add an if condition to the inner part of a nested list comprehension to filter elements, effectively simulating the behavior of a continue statement in traditional nested loops. This is a compact way to perform nested loops in python.

11. Are nested loops efficient for all tasks?

A. While powerful, nested loops can become inefficient for very large datasets or deeply nested structures. In those cases, consider alternative approaches like vectorization with NumPy or different data structures. However, for many common tasks, nested loops in python offer a clear and effective solution, as illustrated by many nested for loop in python example.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.