The Wayback Machine - https://web.archive.org/web/20240826012110/https://www.geeksforgeeks.org/python-nested-loops/
Open In App

Python Nested Loops

Last Updated : 09 Aug, 2024
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

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
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
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
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
For Loops in Python
The For Loops in Python are a special type of loop statement that is used for sequential traversal. Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary.  In Python, there is no C style for loop, i.e., for (i=0; I &lt;n; i++). The For Loops in Python is similar to each loop in other languages, used f
8 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
6 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
Python Nested Dictionary
A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means putting a dictionary inside another dictionary. Ne
3 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
Python: Update Nested Dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Refer to the below article to get the idea about dictionaries: Python Dictionary Nested Dictionary: The nested diction
6 min read
Overriding Nested Class members in Python
Overriding is an OOP's (object-oriented programming) concept and generally we deal with this concept in Inheritance. Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes
2 min read
Python - Nested dictionary Combinations
Sometimes, while working with Python dictionaries, we can have a problem in which we need to construct all the combination of dictionary keys with different values. This problem can have application in domains such as gaming and day-day programming. Lets discuss certain way in which we can perform this task. Input : test_dict = {'gfg': {'is' : [6],
3 min read
Nested Decorators in Python
Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value. Nesting means placing or storing inside the other. Th
2 min read
Nested Lambda Function in Python
Prerequisites: Python lambda In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then it is called Nested Lambda Function. Example 1: #
2 min read
Convert Python Nested Lists to Multidimensional NumPy Arrays
Prerequisite: Python List, Numpy ndarray Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists. Method 1: Using numpy.array(). Approach : Import numpy package.Initialize the nested list and
2 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
Creating nested dataclass objects in Python
Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator
3 min read
How to iterate through a nested List in Python?
In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List. Iterating through a Nested List Lets us see how a typical nested list
2 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
Convert a nested for loop to a map equivalent in Python
In this article, let us see how to convert a nested for loop to a map equivalent in python. A nested for loop's map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between. Syntax:
3 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a diction
3 min read
Rename Nested Field in Spark Dataframe in Python
In this article, we will discuss different methods to rename the columns in the DataFrame like withColumnRenamed or select. In Apache Spark, you can rename a nested field (or column) in a DataFrame using the withColumnRenamed method. This method allows you to specify the new name of a column and returns a new DataFrame with the renamed column. Requ
3 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Python Pandas - Flatten nested JSON
It is general practice to convert the JSON data structure to a Pandas Dataframe as it can help to manipulate and visualize the data more conveniently. In this article, let us consider different nested JSON data structures and flatten them using inbuilt and custom-defined functions. Python Pandas.json_normalize() SyntaxPandas have a nice inbuilt fun
5 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read
Nested List Comprehensions in Python
List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Nested List Comprehension in Python SyntaxBelow is the
5 min read
Article Tags :
Practice Tags :