Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ”„ Python Nested For Loop: Step-by-Step Guide

Python Nested For Loop - Step-by-Step Guide

A nested for loop is simply a loop inside another loop. Follow this step-by-step guide to master them.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • Welcome: Why Nested Loops?
  • Step 1: Understanding the Concept
  • Step 2: Syntax & Structure
  • Step 3: How They Execute
  • Step 4: Star Patterns
  • Step 5: Number Patterns
  • Step 6: Multiplication Table
  • Step 7: Working with Matrices
  • Step 8: Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What nested for loops are — a loop inside another loop
  • How to write them — correct syntax and structure
  • How they execute — understanding the flow
  • Creating star patterns — classic beginner exercise
  • Number patterns — building logical sequences
  • Multiplication tables — a practical use case
  • Working with matrices — processing 2D data
  • Common mistakes — and how to avoid them

Welcome: Why Nested Loops?

šŸ“– Think of it this way: Imagine you're arranging books on shelves. The outer loop goes through each shelf. The inner loop goes through each book on that shelf. You can't arrange books without knowing both which shelf you're on and which book you're placing. That's exactly what nested loops do!

A nested for loop is a for loop inside another for loop. This powerful concept lets you work with multi-dimensional data — like tables, grids, or matrices. When you need to repeat an action multiple times within another repeated action, nested loops are your solution.

šŸ’” Key insight: The inner loop completes all its iterations for each single iteration of the outer loop. Think of it like a clock: the outer loop is the hour hand (slow), the inner loop is the minute hand (fast). The minute hand completes a full cycle for each hour.

Step 1: Understanding the Concept

1

What's Really Happening?

Before we write code, let's understand the concept with a real-world analogy.

Imagine you have 3 classrooms, each with 4 students.
You want to say "Hello" to every student in every classroom.

Outer loop: Go to each classroom (3 times)
Inner loop: Say "Hello" to each student in that classroom (4 times)

Total greetings = 3 Ɨ 4 = 12
This is exactly what nested loops do! The outer loop handles the major groups (classrooms), and the inner loop handles the items within each group (students). The inner loop runs completely for each outer loop iteration.

āœ… Quick Check: If you have 5 classrooms with 6 students each, how many total greetings? (Answer: 5 Ɨ 6 = 30)

Step 2: Syntax & Structure

2

How Do You Write One?

The syntax is simple — just put one for loop inside another:

for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        # This runs for each outer iteration
        print(outer_variable, inner_variable)

Breakdown:

  • Outer loop — controls the major iteration (rows)
  • Inner loop — runs completely for each outer iteration (columns)
  • Indentation — inner loop must be indented inside the outer loop

āœ… Quick Check: What's wrong with: for i in range(3): for j in range(3): print(i, j) (Answer: Missing colon after the inner for loop)

Step 3: How They Execute

3

Following the Flow

Let's trace the execution step by step:

for i in range(1, 4):      # Outer loop: i = 1, 2, 3
    for j in range(1, 4):  # Inner loop: j = 1, 2, 3
        print(f"({i},{j})", end=" ")
    print()  # New line after inner loop

# Execution flow:
# 1. i = 1 → inner loop runs: (1,1), (1,2), (1,3) → new line
# 2. i = 2 → inner loop runs: (2,1), (2,2), (2,3) → new line
# 3. i = 3 → inner loop runs: (3,1), (3,2), (3,3) → new line

# Output:
# (1,1) (1,2) (1,3)
# (2,1) (2,2) (2,3)
# (3,1) (3,2) (3,3)

Key insight: The inner loop completes all its iterations before the outer loop moves to the next iteration. This creates a grid pattern!

āœ… Quick Check: If outer loop runs 4 times and inner loop runs 3 times, how many total inner loop executions? (Answer: 4 Ɨ 3 = 12)

Step 4: Star Patterns

4

Creating a Right Triangle of Stars

This is the classic first exercise for nested loops:

rows = 5

for i in range(1, rows + 1):   # Outer: controls rows
    for j in range(1, i + 1):  # Inner: controls columns (stars)
        print("*", end="")     # Print star on same line
    print()                    # Move to next line

# Output:
# *
# **
# ***
# ****
# *****

Why does this work?

  • When i = 1, the inner loop runs once → 1 star
  • When i = 2, the inner loop runs twice → 2 stars
  • When i = 3, the inner loop runs three times → 3 stars
  • Each row has exactly i stars

āœ… Quick Check: How would you make an inverted triangle (5 stars, then 4, then 3...)? (Hint: Make the outer loop go backwards: for i in range(rows, 0, -1))

Step 5: Number Patterns

5

Creating a Number Triangle

Now let's print numbers instead of stars:

rows = 5

for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end=" ")  # Print numbers 1 to i
    print()

# Output:
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5

What changed? Instead of printing a star, we print the value of j. Since j goes from 1 to i, we get a triangle of numbers. This is a stepping stone to more complex patterns.

āœ… Quick Check: How would you print a triangle of consecutive numbers (1, 2 3, 4 5 6...)? (Hint: Use a separate counter variable that increments each time)

Step 6: Multiplication Table

6

Building a Multiplication Table

A practical use case for nested loops:

for i in range(1, 11):
    for j in range(1, 11):
        print(f"{i * j:4}", end="")  # Each number takes 4 spaces
    print()  # New line after each row

# Output (first few rows):
#    1   2   3   4   5   6   7   8   9  10
#    2   4   6   8  10  12  14  16  18  20
#    3   6   9  12  15  18  21  24  27  30

What's happening:

  • Outer loop: i goes from 1 to 10 (rows)
  • Inner loop: j goes from 1 to 10 (columns)
  • i * j gives the product
  • :4 formatting aligns the numbers neatly

Step 7: Working with Matrices

7

Processing 2D Data

Nested loops are essential for working with matrices (2D lists):

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Print the matrix
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

# Output:
# 1 2 3
# 4 5 6
# 7 8 9

# Calculate sum of all elements
total = 0
for row in matrix:
    for element in row:
        total += element
print(f"Total sum: {total}")
# Output: Total sum: 45

Real-world applications:

  • Image processing (pixels)
  • Game development (grids)
  • Data analysis (tables)
  • Scientific computing (matrices)

Step 8: Common Mistakes to Avoid

8

Watch Out For These!

āŒ Mistake 1: Using the Same Variable

Don't reuse the same variable name in both loops:

# WRONG (using 'i' in both loops)
for i in range(3):
    for i in range(3):  # This will cause problems!
        print(i)

# CORRECT (using different variables)
for i in range(3):
    for j in range(3):
        print(i, j)

āŒ Mistake 2: Forgetting to Indent

Python uses indentation to define blocks. Incorrect indentation changes the logic:

# WRONG (inner loop not indented)
for i in range(3):
print(i)  # Not inside the loop!

# CORRECT (proper indentation)
for i in range(3):
    print(i)

āŒ Mistake 3: Not Resetting Inner Variable

If you're using while loops inside for loops, remember to reset the inner counter:

# WRONG (j keeps increasing)
i = 1
while i <= 3:
    j = 1  # ← Important: Reset j here!
    while j <= i:
        print("*", end="")
        j += 1
    print()
    i += 1

Try It Yourself!

Experiment with nested for loops directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
NESTED FOR LOOP - PRACTICE
========================================

1. SIMPLE GRID (3x3)
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

2. STAR PATTERN
*
**
***
****
*****

3. NUMBER TRIANGLE
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

4. MULTIPLICATION TABLE (5x5)
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

5. MATRIX SUM
Total: 45

āœ… Now try creating your own patterns!
šŸ†

šŸŽ‰ You've Mastered Nested For Loops!

You understand nested for loop syntax, patterns, multiplication tables, and matrix operations. This is a powerful skill for complex data processing!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about nested for loops:

1. In a nested for loop, which loop runs completely for each iteration of the other?
2. What does the outer loop typically control in a nested loop?
3. What's the output of: for i in range(2): for j in range(2): print(i, j)?
4. What happens if you use the same variable name in both outer and inner loops?
5. Which is a correct use of a nested for loop?

Frequently Asked Questions

šŸ¤” How many levels of nested loops should I use? ā–¼

Generally, you should limit nesting to 2-3 levels maximum. More than 3 levels makes code difficult to read, debug, and maintain. If you need more levels, consider breaking the logic into smaller functions or using recursion.

šŸ”§ What is the time complexity of a nested loop? ā–¼

The time complexity of a nested loop with an outer loop of size n and an inner loop of size m is O(n Ɨ m). If both loops run n times, the complexity is O(n²). This is important for performance, especially with large datasets.

šŸ“ Can I nest a for loop inside a while loop? ā–¼

Yes! You can nest different types of loops. A for loop can be nested inside a while loop, and vice versa. This flexibility allows you to use the best loop type for each level of iteration.

šŸ“Š How do I break out of multiple nested loops? ā–¼

The break statement only exits the innermost loop. To break out of multiple levels, you can use a flag variable or wrap the loops in a function and use return. Alternatively, you can use a for-else construct with a flag.

⚔ What's the difference between nested loops and nested comprehensions? ā–¼

Nested loops are a general programming construct for iteration. Nested comprehensions are a Python-specific, more concise way to create lists, sets, or dictionaries from nested sequences. For example, [i*j for i in range(3) for j in range(3)] is a nested list comprehension.

šŸŽÆ What's a real-world example of nested loops? ā–¼

Common examples include: (1) Processing 2D arrays/matrices, (2) Creating multiplication tables, (3) Generating patterns (pyramids, triangles), (4) Image processing (pixels), (5) Game development (grid-based games), and (6) Data analysis (cross-tabulations).

šŸ“š Where to Go From Here

Now that you've mastered nested for loops, here are the next topics to explore:

šŸ“Š Nested For Loop Examples

Explore more advanced nested for loop examples.

Learn More →

⚔ Break, Continue, Else

Learn how to control loop execution with break and continue.

Learn More →

šŸ”„ For vs While

Understand the differences between for and while loops.

Learn More →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: For Loop Examples Next: Nested For Loop Examples →