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
  1. Home
  2. Tutorials
  3. Software & Tech
  4. Nested for loop in Python
python

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

  • 201 Lessons
  • 33 Hours
right-top-arrow

Tutorial Playlist

200 Lessons
16

Nested for loop in Python

Updated on 17/10/20246,398 Views

Introduction

A versatile and extensively employed programming language, Python equips developers with a multitude of tools and methods for efficiently managing intricate tasks. Among these tools are nested for loops, which constitute a formidable resource in Python's toolkit. These loops offer a methodical approach to addressing repetitive tasks, particularly when the requirement involves traversing multiple sequences or executing complex operations. This all-encompassing guide will immerse you in the realm of nested for loop in Python, dissecting their syntax, presenting a variety of examples, and illustrating the utilization of break and continue statements within these loop structures.

Overview

A nested loop, found within another loop, empowers you to incorporate one or more loops within the parent loop. In Python, this programming construct provides a remarkable level of adaptability, granting you the capacity to effectively address repetitive tasks frequently associated with intricate and multifaceted data structures or sequences. By nesting loops, you can navigate through multidimensional data, perform various operations on each combination of elements, and handle scenarios where you need to work with elements within elements. This versatile approach empowers Python developers to create structured, organized, and powerful code for a wide range of applications, from iterating through matrices to generating intricate patterns and working with nested data structures.

Python Nested Loops Syntax

The syntax of a nested loop in Python provides a structured way to work with repetitive tasks that involve multiple sequences or complex data structures. A nested loop consists of one loop encapsulated within another, and it can be represented as follows:

for outer_loop_variable in outer_sequence:

    # Outer loop code

    for inner_loop_variable in inner_sequence:

        # Inner loop code

Outer Loop: The outer loop is defined using the for keyword, followed by an outer_loop_variable, which represents the variable that takes on values from the outer_sequence.

Outer Loop Code: The code specific to the outer loop is indented beneath it. This code executes for each iteration of the outer loop and typically involves actions or decisions related to the elements of the outer_sequence.

Inner Loop: Inside the outer loop, there's another for loop, known as the inner loop. This for loop inside for loop is defined with its own inner_loop_variable, which takes on values from the inner_sequence.

Inner Loop Code: The code associated with the inner loop is indented beneath it. This code executes for each iteration of the inner loop.

Python Nested Loops Examples

Now, let's dive into some examples to understand how nested loops work in Python.

Example 1: Basic Example of Python-Nested Loops

python code
# Using nested loops to print a pattern

for i in range(3):

    for j in range(3):

        print(i, j)

In this example, we have two loops: an outer loop for i in range(3) and an inner loop for j in range(3). The outer loop iterates from 0 to 2, and for each value of i, the inner loop iterates from 0 to 2. As a result, this code prints combinations of i and j.

Example 2: Printing Multiplication Table Using Python Nested For Loops

python code
# Printing the multiplication table of 5

for i in range(1, 11):

    for j in range(1, 11):

        product = i * j

        print(f"{i} x {j} = {product}")

In this example, we use 3 nested for loops Python to print the multiplication table of 5. The outer loop iterates over the numbers from 1 to 10, representing the first factor. The inner loop also iterates from 1 to 10, representing the second factor. The product of i and j gives the result, and it is printed as part of the table.

Example 3: Printing Using Different Inner and Outer Nested Loops

python code
# Printing patterns using different inner and outer nested loops
for i in range(5):
    for j in range(i):
        print("*", end=" ")
    print()

In this example, we create a pattern using nested loops. The outer loop iterates over the numbers from 0 to 4, controlling the number of asterisks to be printed on each line. The inner loop iterates from 0 to i, printing the asterisks on the same line without moving to the next line. The end=" " parameter in the print function ensures that spaces are used instead of line breaks to separate the asterisks.

Using Break Statements in Nested Loops

In Python, the break statement serves as a valuable instrument, granting you the capability to prematurely exit a loop, thus circumventing any subsequent iterations. This functionality proves exceptionally advantageous, especially in the context of nested loops, as it permits the termination of both the inner and outer loops upon the satisfaction of certain conditions.

Consider the following Python code:

# Using break in nested loops
for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            break
        print(i, j)

In this code snippet, nested for loops Python lists are employed. The outer loop, defined by for i in range(3):, iterates over a sequence of numbers from 0 to 2. Within this outer loop, we have an inner loop: for j in range(3):, which iterates over the same range of numbers.

Now, the power of the break statement is evident within the inner loop. We've incorporated a conditional statement: if i == 1 and j == 1:. This condition checks whether the values of i and j are both equal to 1. If this condition is satisfied, the break statement is executed.

When the break statement is triggered, it serves as an abrupt exit from the inner loop. It effectively skips any remaining iterations of the inner loop and returns to the outer loop. Importantly, the execution of the outer loop is not affected by the break statement within the inner loop.

Here's how the code behaves step by step:

The outer loop starts with i equal to 0.

  • The inner loop is initiated with j equal to 0, printing 0 0.
  • The inner loop continues with j equal to 1, but when the condition i == 1 and j == 1 is met, the inner loop breaks.
  • The program returns to the outer loop.
  • The outer loop continues with i equal to 0, then 1, and finally 2. For i equal to 1, the inner loop is terminated when j is 1 (as we observed earlier), but for other values of i, the inner loop runs its course.

The result is that the code prints the following pairs of numbers:

0 0, 0 1, 0 2, 2 0, 2 1, 2 2

The key takeaway is that the break statement is a powerful tool for exiting loops prematurely when specific conditions are met. In the context of nested loops, it helps you control the flow of your program and provides flexibility for handling complex iterations.

In this example, it terminated the inner loop when i and j equaled 1. However, if you had other conditions or requirements in your code, you could use the break statement to tailor the behavior of your loops accordingly.

Using Continue Statement in Nested Loops

The continue statement is used to skip the rest of the current iteration of a loop and proceed to the next iteration. It can be beneficial in nested while loop in Python when you want to skip certain iterations while continuing with the remaining iterations. Here's an example:

python code
# Using continue in nested loops
for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            continue
        print(i, j)

Single-line Nested Loops Using List Comprehension

List comprehensions, a powerful and concise feature offered by Python, enable the creation of compact, single-line nested loops to generate lists or other iterables. They come in particularly handy when you're tasked with producing lists derived from combinations or alterations of elements originating from one or multiple sequences.

new_list = [expression for item in iterable]

expression: The expression that specifies how to transform or filter items from the iterable.

item: The variable representing each element in the iterable.

iterable: The sequence from which elements are drawn.

Now, let's dive into the nested loop example you provided:

# Single-line nested loops using list comprehension

nested_list = [(i, j) for i in range(3) for j in range(2)]

print(nested_list)

In this example, you are creating a list of tuples (i, j) using list comprehension. Here's a step-by-step explanation:

[(i, j): This part defines the expression that specifies the elements to include in the resulting list. In this case, you want to create tuples (i, j).

for i in range(3): The first for clause iterates over the values of i in the range from 0 to 2 (inclusive).

for j in range(2): The second for clause is nested inside the first one and iterates over the values of j in the range from 0 to 1 (inclusive).

When you combine these for clauses within the list comprehension, you are effectively generating all combinations of i and j. The resulting nested_list contains the following tuples:

css code
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

As you can see, this concise one-liner effectively replaces traditional nested loops, making your code more readable and compact while achieving the same result.

Conclusion

Python nested for loops, a powerful feature, enable you to efficiently handle complex data structures and carry out repetitive tasks. Once you grasp their syntax and application, they empower you to craft well-structured and organized code. You've learned how to create basic patterns, print multiplication tables, and use break and continue statements in nested loops. Additionally, we explored single-line nested loops using list comprehensions, providing a more concise way to achieve the same results.

FAQs

1. What is a Python nested loop?

A nested loop involves one loop contained within another, with the inner loop executed as the outer loop begins its initial iteration. The inner loop will then be triggered again by the outer loop's second run.

2. What is the difference between break and continue in nested loops?

break statement is used to exit the entire loop prematurely and continue is used to skip the rest of the current iteration and proceed to the next iteration of the loop.

3. Can I nest loops of different types in Python?

Yes, you can nest loops of different types, such as for, while, and even mixed types, depending on your requirements.

4. Are nested loops inefficient?

Nested loops can be less efficient for large datasets, as they lead to higher time complexity. It's important to analyze the performance of your code and consider alternative approaches, such as using built-in functions or list comprehensions.

5. What are some practical use cases for nested loops?

Nested loops are commonly used for tasks like searching in multi-dimensional arrays, generating combinations or permutations, and working with nested data structures.

6. What is the Python equivalent of a nested for loop?

Another helpful feature of the itertools module is the chain. If we have many variables and wish to loop over them consecutively as if they were just one iterable, we should use chains rather than nested loops.

Ready to challenge yourself? Take our Free Python Quiz!

image
Need More Help? Talk to an Expert
form image
+91
*
By clicking Submit, I accept theT&Cand
Privacy Policy
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

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

  1. upGrad facilitates program delivery and is not a college/university in itself. Credits and credentials are awarded by the university. Please refer relevant terms and conditions before applying.

  2. Past record is no guarantee of future job prospects.