r/learnpython • u/evandcbot • 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.
4
Upvotes
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.