Nearby lessons

50 of 108

Python - Nested Loops

What Are Nested Loops?

Nested loops mean placing one loop inside another loop.

The inner loop runs fully for each outer loop iteration.

Why Use Them?

Nested loops are useful for pattern printing, matrix processing, and table generation.

Nested for Loop

A Nested Loop means placing one loop inside another loop.

The inner loop executes completely for every iteration of the outer loop.

Syntax

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
No output captured.

Example 1 - Nested Loop

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2

Understanding Nested Loop

For every value of i, the inner loop runs completely.

After the inner loop finishes, the outer loop moves to the next value.

Example 2 - Print Rectangle Pattern

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
* * * * *
* * * * *
* * * * *
* * * * *

Example 3 - Multiplication Table

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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

Difference Between Single Loop and Nested Loop

Single Loop Nested Loop
Contains only one loop. Contains one loop inside another loop.
Less repetition. More repetition.
Simple iteration. Useful for tables, matrices, and patterns.

Important Notes

  • Tuple elements are processed one by one.
  • Set elements are unordered, so the output order may change.
  • Dictionary loops return keys by default.
  • Use items() to access both keys and values.
  • A nested loop means one loop inside another loop.
  • The inner loop executes completely for every iteration of the outer loop.
  • Nested loops are commonly used for pattern printing, matrices, and multiplication tables.

Quick Summary

Sequence Iteration Result
Tuple Reads each element one by one.
Set Reads each element (unordered).
Dictionary Returns keys by default.
items() Returns both keys and values.
Nested Loop Loop inside another loop.

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!Python - Break Statement