# B: What are Nested Loops in Python?

*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.

![](https://cdn.hashnode.com/uploads/covers/6a045b1b5418a55a522a6d57/c521b28e-8f77-4577-b878-dfbfa66dd9f3.png align="center")

![](https://cdn.hashnode.com/uploads/covers/6a045b1b5418a55a522a6d57/ee1ecb8c-8809-4311-96f9-e254565c2c0a.png align="center")

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:

![](https://cdn.hashnode.com/uploads/covers/6a045b1b5418a55a522a6d57/4fd73295-9156-4c55-926a-421f64772c8b.png align="center")

![](https://cdn.hashnode.com/uploads/covers/6a045b1b5418a55a522a6d57/0d33f095-db4c-43f3-9fce-ebdd5310a747.png align="center")

### `break` and `continue` Affect Only the Inner Loop

![](https://cdn.hashnode.com/uploads/covers/6a045b1b5418a55a522a6d57/98e737a4-31c7-4b1c-94e5-4b925bff887c.png align="center")

![](https://cdn.hashnode.com/uploads/covers/6a045b1b5418a55a522a6d57/8e098043-beda-4a07-8569-890a231a9011.png align="center")

`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*
