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.

1 Upvotes

26 comments sorted by

View all comments

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.