Open In App

Python Nested Loops

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc.

Python Nested Loops

Python Nested Loops

Python Nested Loops Syntax:

Outer_loop Expression:

    Inner_loop Expression:

        Statement inside inner_loop

    Statement inside Outer_loop

Python Nested Loops Examples

Example 1: Basic Example of Python Nested Loops

Python
x = [1, 2]
y = [4, 5]

for i in x:
  for j in y:
    print(i, j)

Output:

1 4
1 5
2 4
2 5
Python
x = [1, 2]
y = [4, 5]
i = 0
while i < len(x) :
  j = 0
  while j < len(y) :
    print(x[i] , y[j])
    j = j + 1
  i = i + 1

Time Complexity: O(n2)

Auxiliary Space: O(1)

Example 2: Printing multiplication table using Python nested for loops

Python
# Running outer loop from 2 to 3

for i in range(2, 4):

    # Printing inside the outer loop
    # Running inner loop from 1 to 10
    for j in range(1, 11):

        # Printing inside the inner loop
        print(i, "*", j, "=", i*j)
    # Printing inside the outer loop
    print()

Output:

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20


3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

Time Complexity: O(n2)

Auxiliary Space: O(1)

In the above example what we do is take an outer for loop running from 2 to 3 for multiplication table of 2 and 3 and then inside that loop we are taking an inner for loop that will run from 1 to 10 inside that we are printing multiplication table by multiplying each iteration value of inner loop with the iteration value of outer loop as we see in the below output.

Example 3: Printing using different inner and outer nested loops

Python
# Initialize list1 and list2
# with some strings
list1 = ['I am ', 'You are ']
list2 = ['healthy', 'fine', 'geek']

# Store length of list2 in list2_size
list2_size = len(list2)

# Running outer for loop to
# iterate through a list1.
for item in list1:
  
    # Printing outside inner loop
    print("start outer for loop ")
    # Initialize counter i with 0
    i = 0
    # Running inner While loop to
    # iterate through a list2.
    while(i < list2_size):
      
        # Printing inside inner loop
        print(item, list2[i])
        # Incrementing the value of i
        i = i+1
    # Printing outside inner loop
    print("end for loop ")

Output:

start outer for loop
I am healthy
I am fine
I am geek

end for loop

start outer for loop

You are healthy
You are fine
You are geek

end for loop

Time Complexity: O(n2)

Auxiliary Space: O(1)

In this example, we are initializing two lists with some strings. Store the size of list2 in ‘list2_Size’ using len() function and using it in the while loop as a counter. After that run an outer for loop to iterate over list1 and inside that loop run an inner while loop to iterate over list2 using list indexing inside that we are printing each value of list2 for every value of list1.

Using break statement in nested loops

It is a type of loop control statement. In a loop, we can use the break statement to exit from the loop. When we use a break statement in a loop it skips the rest of the iteration and terminates the loop. let’s understand it using an example.

Code:

Python
# Running outer loop from 2 to 3
for i in range(2, 4):

    # Printing inside the outer loop
    # Running inner loop from 1 to 10
    for j in range(1, 11):
      if i==j:
        break
      # Printing inside the inner loop
      print(i, "*", j, "=", i*j)
    # Printing inside the outer loop
    print()

Output:

2 * 1 = 2

3 * 1 = 3
3 * 2 = 6

Time Complexity: O(n2)

Auxiliary Space: O(1)

The above code is the same as in Example 2 In this code we are using a break statement inside the inner loop by using the if statement. Inside the inner loop if ‘i’ becomes equals to ‘j’ then the inner loop will be terminated and not executed the rest of the iteration as we can see in the output table of 3 is printed up to two iterations because in the next iteration ‘i’ becomes equal to ‘j’ and the loop breaks.

Using continue statement in nested loops

A continue statement is also a type of loop control statement. It is just the opposite of the break statement. The continue statement forces the loop to jump to the next iteration of the loop whereas the break statement terminates the loop. Let’s understand it by using code.

Python
# Running outer loop from 2 to 3
for i in range(2, 4):

    # Printing inside the outer loop
    # Running inner loop from 1 to 10
    for j in range(1, 11):
      if i==j:
        continue
      # Printing inside the inner loop
      print(i, "*", j, "=", i*j)
    # Printing inside the outer loop
    print()

Output:

2 * 1 = 2
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

3 * 1 = 3
3 * 2 = 6
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

Time Complexity: O(n2)

Auxiliary Space: O(1)

In the above code instead of using a break statement, we are using a continue statement. Here when ‘i’ becomes equal to ‘j’ in the inner loop it skips the rest of the code in the inner loop and jumps on the next iteration as we see in the output “2 * 2 = 4” and “3 * 3 = 9” is not printed because at that point ‘i’ becomes equal to ‘j’.

Single line Nested loops using list comprehension

To convert the multiline nested loops into a single line, we are going to use list comprehension in Python. List comprehension includes brackets consisting of expression, which is executed for each element, and the for loop to iterate over each element in the list.

Syntax of List Comprehension:

newList = [ expression(element) for element in oldList if condition ] 

Code:

Python
# Using  list comprehension to make
# nested loop statement in single line.
list1 = [[j for j in range(3)]
         for i in range(5)]
# Printing list1
print(list1)

Output:

[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

In the above code, we are storing a list inside the list using list comprehension in the inner loop of list comprehension [j for j in range(3)] to make a list [0, 1, 2] for every iteration of the outer loop “for i in range(5)”.

Time Complexity: O(n2) It is faster than nested loops

Auxiliary Space: O(n)

Python Nested Loops – FAQs

What is a Nested Loop in Python?

A nested loop in Python refers to a loop within another loop. The “inner loop” will be executed one time for each iteration of the “outer loop”. This structure is commonly used when you need to perform operations on multi-dimensional data structures like lists of lists, or when processing tasks that require multiple levels of looping.

Example of a Nested Loop:

for i in range(1, 4):  # Outer loop
for j in range(1, 4): # Inner loop
print(f'i = {i}, j = {j}')

This will print pairs of i and j values, where i is from the outer loop and j from the inner.

What are the 2 Main Types of Loops in Python?

The two main types of loops in Python are:

  1. For Loop: Used for iterating over a sequence (such as a list, tuple, dictionary, set, or string). It’s a common choice for loops where the number of iterations is determined by the elements in the sequence.
  2. While Loop: Repeats as long as a specified boolean condition is true. It’s used when the number of iterations is not predetermined and needs to continue until a condition changes.

What are the 3 Types of Loops?

Broadly across programming languages, the three types of loops typically referenced are:

  1. For Loop: Iterates over a sequence of elements, performing a block of code multiple times with different values from the sequence each time.
  2. While Loop: Continues looping as long as a condition remains true, often used when the number of iterations is not known before the loop starts.
  3. Do-While Loop: Similar to a while loop, but it guarantees that the loop body will execute at least once because the condition is checked after the loop body executes. Note that Python does not natively support do-while loops, but similar functionality can be mimicked using a while loop.

How Many Nested Loops are There?

In Python, there is no fixed limit to the number of nested loops you can have. However, the readability and complexity of the code should be considered as deeply nested loops can be difficult to read and maintain. Typically, beyond three levels of nesting, it might be better to consider simplifying the approach or using other data structures or algorithms.

What is Nested Class in Python?

A nested class in Python refers to a class defined inside another class. Nested classes are often used for organizing code and encapsulating functionality that is relevant only to the enclosing class, which can enhance code readability and maintainability.

Example of a Nested Class:

class Outer:
class Inner:
def display(self):
print("Hello from the Inner class!")

# Creating an instance of the nested class
inner_instance = Outer.Inner()
inner_instance.display() # Output: Hello from the Inner class!


Previous Article
Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg
  翻译: