Nested Loops

Python · Loops

Theory

A nested loop is a loop inside the body of another loop. For every single pass of the outer loop, the inner loop runs completely from start to finish. In the example the outer loop takes i = 0, and the inner loop prints (0, 0) and (0, 1); then the outer loop takes i = 1 and the inner loop starts over from j = 0. The total number of inner passes is the outer count times the inner count: 2 x 2 = 4 here.

That multiplication is the key performance point. Two nested loops over n items each do n x n work, O(n squared): 1,000 items means a million inner passes, and a third level makes it a billion. A common example is comparing every item with every other item to find duplicates, which a set can do in a single pass. Also remember that break only exits the innermost loop it is in; to stop both loops, use a flag variable, put the loops in a function and return, or restructure with itertools.product.

Why we use it

Some problems are naturally two-dimensional: rows and columns of a grid, every pair of products, each store times each month. Nested loops visit every combination.

When to use it

Use nested loops for grids, matrices and small pairwise comparisons. For large data, look for a faster approach: a set or dict lookup instead of an inner search loop, itertools.product for combinations, or vectorised pandas/NumPy operations.

How it works

  1. Outer loop takes the next i
  2. Inner loop restarts at j = 0
  3. Run the inner body: print(i, j)
  4. More j values? Yes: Next j, run the body again. No: Inner loop finished.
  5. More i values? Yes: Back to the outer loop. No: Both loops done.
  6. Total passes = outer count x inner count

Syntax

for x in outer:
    for y in inner:
        ...

Example

for i in range(2):
    for j in range(2):
        print(i, j)

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic