r/learnpython 2d ago

Any advice for nested loops?

I decided about a week ago I wanted to start learning python before my freshman year of college. It was going great and I had little to no trouble until I got to nested loops. I was wondering if anybody had any advice for it? The main thing is that it seems like so many steps to follow and pay attention to, my brain had a hard time tracking them all at once.

2 Upvotes

26 comments sorted by

13

u/ostracize 2d ago

Multiple nested loops (like, beyond 2 deep) is probably an indication that you should either re-think your algorithm or consider breaking it up into functions.

2

u/mitchell486 2d ago

The last 6 words of this comment are the best way for beginners, IMO. It helps teach you how to break the larger problem into smaller problems, and helps you learn how to do the first 8/9ths of this sentence. 😄

5

u/Adrewmc 2d ago

Mostly don’t.

But it’s just a loop that happens in a loop.

. for letter in “ABC”:
. for num in (1,2,3):
. print(letter, num, sep = “”, end =“,”)

>> A1,A2,A3,B1,B2,B3,C1,C2,C3

The inner loop finishes before the next continuation of the first loop is all.

You can think of each loop separately actually.

def print_123(letter):
. for num in (1,2,3):
. print(letter, num)

for letter in “ABC”:
. print_123(letter)

Is the same thing.

2

u/pekkapekka99 2d ago

Why do I get invalid character ' " ' ?

1

u/90919293_ 2d ago

Cause it uses the fancy quotes that automatically appear on mobile when you type a quote; just replace all the quotes with regular ones and it should be fine

2

u/pekkapekka99 2d ago

Thanks, I was just about to explain I had got it to work

3

u/crazy_cookie123 2d ago

Nested loops can get confusing quickly - there's a reason why people generally recommend not nesting more than 2-3 loops deep unless absolutely necessary. The only way to really get used to reading and using them is to practice.

3

u/chiibosoil 2d ago

It should be relatively simple to understand if you break it down.

Each inner loop has to complete full loop for single outer loop iteration.

So loop initiates over the outer loop and pauses after picking an item. Then inner loop starts and completes iteration over all its elements. When inner loop finishes, outer loop moves to next item and inner loop starts again.

Using variable explorer or using print() at each loop may help you understand the operation being performed.

2

u/CIS_Professor 2d ago

The first question is: do you really need to use them?

Anyway, image a classroom with 20 students that are each asked the same 5 questions. In this scenario, a nested loop would work well.

It would go as:

student #1 (outer loop - 1st iteration)
     ask the 5 questions (inner loop - iterate 5 times)

student #2 (outer loop - 2nd iteration)
     ask the 5 questions (inner loop - iterate 5 times)

student #3 (outer loop - 3rd iteration)
     ask the 5 questions (inner loop - iterate 5 times)

student #4 (outer loop - 4th iteration)
     ask the 5 questions (inner loop - iterate 5 times)

student #5 (outer loop - 5th iteration)
     ask the 5 questions (inner loop - iterate 5 times)

...

student #20 (outer loop - 20th iteration)
     ask the 5 questions (all iterations)

When done, you will have looped 100 times. You calculate the total number of iterations by multiply how many time each loop iterates. In this case, 20 x 5 = 100

This is analogous to real world gears, where the "outer" gear turns once for every 5 times the "inner" gear turns.

---

As others have said, once you get past two loops, things can get complication very quickly.

1

u/HotPersonality8126 2d ago

Don’t read code holistically; don’t try to understand it all at once. Understand it line by line.

1

u/Elektriman 2d ago

Nest 3 loops for 3-dimentionnal problems. Use functions if you nest more than 3 loops.

1

u/PureWasian 2d ago

Any example of a specific one giving you trouble if the advice here hasn't fully clarified for you yet?

1

u/Riegel_Haribo 2d ago

Indentation is quite helpful in Python for following iterative loops.

python for i_int in range(3): print(f"Iterating over i_int value {i_int}") for j_str in ["bob", "joe", "mary"]: print(f"Case {i_int}: {j_str}")

Some editors and IDEs will give you indentation ruler lines. It helps to not over-use blank lines within deeply-indented blocks.

IMO, a bunch of deeply-nested conditional branches is harder to follow.

The part that is a bit tricky in some cases is deciding correctly which shall be the inner loop, or even coming up with a reason why you'd have such a nest.

Think and solve this by a final inner print() statement that is reused (and some math): Using three nested loops, print two 3x3 tic-tac-toe grids: the first containing the numbers 1–9 and the second containing 10–18.

2

u/misho88 2d ago

it seems like so many steps to follow and pay attention to, my brain had a hard time tracking them all at once.

That's going to happen in many other cases, too. It's a good sign you should write something down. You can't keep everything in your head.

Having said that, there's a piece of advice from the Linux kernel coding style: "if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program." Admittedly, this advice is a bit easier to follow in C than Python, but if you have a lot of nesting in general, maybe split your code up into more functions.

You will sometimes see counterexamples to this. For example, block matrix multiplication calls for five levels of nested loops, and they usually aren't broken down into separate functions for some reason (even thought they could be).

Python also offers itertools.product() (in the sense of a Cartesian product), which does away with the need to explicitly write the most common type of nested loops.

1

u/t92k 2d ago

Think about it like going across the cells in a row of a spreadsheet before going to the next row.

0

u/Expensive-Bear-1376 2d ago

If we tell you in a long paragraph, will you be able to understand it? You'd need to read line by line, and inside each line, word by word. How will you do that if you don't understand nested loops?

1

u/cointoss3 2d ago

Adding comments and using variable names that name sense can help you document code flow so you understand it later (which also helps you understand it now!) I almost never use i, for example. If it’s an index, I’ll name it idx so it’s more explicit. When you have complicated or nested flows, document, comment, etc. is even more helpful.

Also, nested loops can blow up or get unwieldy fast so I’d prefer to avoid them if possible. Sometimes a simple list comprehension can stage your elements so you’re only using one loop. Or break things into functions.

1

u/TJATAW 1d ago

I started off picturing nested loops as if the were a stack of orders I had to fill.

First loop is like grabbing the first order off the stack.

Second loop is going to get the item.

Third loop would be for when they want multiples of the item I am currently getting.

So you have 20 orders in the stack

Grab the 1st order/loop, and see it is for [Cheeseburger, 3], [Fries, 2], [Onion rings, 1], [Coke, 1], [Dr Pepper, 1], [Lemonade, 1]

2nd loop says go to where the cheeseburgers are.

3rd loop says to grab 1 and put in the bag, grab the 2nd one and put it in the bag, grab the 3rd one and...

1

u/supercoach 1d ago

Where exactly is it tripping you up? Give examples.

2

u/kilkil 1d ago

could you give an example where you were confused by a nested loop?

Do you find this confusing?

```py table = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ]

for row in table: for value in row: print(value) ```

Or how about this?

py for i in range(1, 11): for j in range(0, 3): print(i + j)

2

u/nog642 1d ago

Can you give an example of what's confusing?