Open In App

Python Nested Loops

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Python3




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

Python3




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

Python3




# 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

Python3




# 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:

Python3




# 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.

Python3




# 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:

Python3




# 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)



Previous Article
Next Article

Similar Reads

Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
How to make a box with the help of nested loops using Python arcade?
Arcade library is modern framework currently used in making 2D games. Nested loop discussed here are analogous to nested loops in any other programming language. The following tutorial will step by step explain how to draw a box with the help of nested loops using Python's arcade module. Import arcade library.Here we will be using circles to form a
2 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Output of Python Programs | Set 22 (Loops)
Prerequisite: Loops Note: Output of all these programs is tested on Python3 1. What is the output of the following? mylist = ['geeks', 'forgeeks'] for i in mylist: i.upper() print(mylist) [‘GEEKS’, ‘FORGEEKS’]. [‘geeks’, ‘forgeeks’]. [None, None]. Unexpected Output: 2. [‘geeks’, ‘forgeeks’] Explanation: The function upper() does not modify a string
2 min read
Specifying the increment in for-loops in Python
Let us see how to control the increment in for-loops in Python. We can do this by using the range() function. range() function range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well
2 min read
How to Break out of multiple loops in Python ?
In this article, we will see how to break out of multiple loops in Python. For example, we are given a list of lists arr and an integer x. The task is to iterate through each nested list in order and keep displaying the elements until an element equal to x is found. If such an element is found, an appropriate message is displayed and the code must
6 min read
Use for Loop That Loops Over a Sequence in Python
In this article, we are going to discuss how for loop is used to iterate over a sequence in Python. Python programming is very simple as it provides various methods and keywords that help programmers to implement the logic of code in fewer lines. Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, s
3 min read
Python Do While Loops
In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is initially True and then break out of
3 min read
Output of Python program | Set 15 (Loops)
Prerequisite - Loops in Python Predict the output of the following Python programs. 1) What is the output of the following program? x = ['ab', 'cd'] for i in x: i.upper() print(x) Output: ['ab', 'cd'] Explanation: The function upper() does not modify a string in place, but it returns a new string which here isn’t being stored anywhere. So we will g
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg