PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Nested Loops in Python

Nested Loops in Python

Updated on: September 2, 2021 | 40 Comments

In Python, a loop inside a loop is known as a nested loop. In this tutorial, we will learn about nested loops in Python with the help of examples.

Also, Solve:

  • Python loop Exercise
  • Python loop Quiz

Table of contents

  • What is a Nested Loop in Python?
  • Python Nested for Loop
    • Nested Loop to Print Pattern
    • While loop inside a for loop
    • Practice: Print a rectangle Pattern with 5 rows and 3 columns of stars
  • Break Nested loop
  • Continue Nested loop
  • Single Line Nested Loops Using List Comprehension
  • Nested while Loop in Python
    • for loop inside While loop
  • When To Use a Nested Loop in Python?

What is a Nested Loop in Python?

A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type, such as a while loop or for loop. For example, the outer for loop can contain a while loop and vice versa.

The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops.

In the nested loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop.

In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an outer loop the inner loop re-start and completes its execution before the outer loop can continue to its next iteration.

Nested loops are typically used for working with multidimensional data structures, such as printing two-dimensional arrays, iterating a list that contains a nested list.

A nested loop is a part of a control flow statement that helps you to understand the basics of Python.

Python Nested for Loop

In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other iterable objects such as range.

Syntax of using a nested for loop in Python

# outer for loop
for element in sequence 
   # inner for loop
   for element in sequence:
       body of inner for loop
   body of outer for loopCode language: Python (python)

In this example, we are using a for loop inside a for loop. In this example, we are printing a multiplication table of the first ten numbers.

  • The outer for loop uses the range() function to iterate over the first ten numbers
  • The inner for loop will execute ten times for each outer number
  • In the body of the inner loop, we will print the multiplication of the outer number and current number
  • The inner loop is nothing but a body of an outer loop.