Skip to main content

Command Palette

Search for a command to run...

B: What are Nested Loops in Python?

Updated
•3 min read•View as Markdown
B: What are Nested Loops in Python?
W
Computer System Engineer, Python Developer and Aspiring Cybersecurity professional

By Waqas Hussain (GlitchWH) Computer System Engineering student specializing in Python and Cyber Security

Introduction

A nested loop is a loop placed inside another loop. It is how Python works with rows and columns, grids, tables, and combinations of items.

its like first write 1 okay, the multiply numbers with it from 1 to 3, since 4 here is stop.
so it will be like this:
1 x 1, 1 x 2, 1 x 3 = 1 2 3, then empty print to start next row.
then for 2nd loop the 1 changes to 2 okay.
2 x 1, 2 x 2, 2 x 3 = 2 4 6, then empty print to start the next row.

for 3rd loop the number changes from 2 to 3, so here is the final step.
3 x 1, 3 x 2, 3 x 3 = 3 6 9 and bang the nested loop finishes.

Total Iterations

The inner body runs outer count × inner count times. Here that is 3 × 3 = 9. Nested loops multiply work, so on large data they get slow quickly. Two loops of 1,000 items each means 1,000,000 runs.

The Inner Loop Can Depend on the Outer One

The inner range can use the outer loop variable:

break and continue Affect Only the Inner Loop

break stops only the inner loop. The outer loop continues with its next value.
here is the break down for this:

so the outer loop will will from 0 - 2, a total of 3 steps.
the inner loop is intended to run 3 steps too from 0-2, but in next line we placed a condition there if j = 1, then look should break.
so for 1st loop everything is good to go, its like pairing two blocks together.
During this whole process the CPU constantly checks if the j is 1 or not, as the 0 1 reaches it directly breaks without even printing it, so the program acutally stops at 0 1 but we see 2 0, thats because the print statement comes after the break statement.

Conclusion

In nested loops, the inner loop completes fully on every outer iteration, and total runs equal outer × inner. The inner loop can depend on the outer variable, break and continue affect only the innermost loop, and return is the clean way to exit both.

Next up: C: Mixing Loops and Conditionals in Python

More from this blog

G

Glitch(WH)InTheCode

11 posts

About GlitchWH: Welcome to GlitchWH, a tech blog exploring Python development and cybersecurity.We start at the absolute beginner level—breaking down basic scripts,codes and security concepts step-by-step. Over time, we will progress together into advanced automation, Defensive Mastery, and DevSecOps.Whether you are writing your first line of code or learning to defend networks, this is your practical roadmap to mastering secure scripting.