Original: Trey Hunner
Because Python’s “for” loop works differently, new Python programmers often get confused about what the most “Pythonic” way to solve various looping problems is. The way you’d solve particular looping problems in C may greatly differ from the way you’d solve the same problem in Python.
Our general approach to looping is “if you need to do something while you loop, look out for a looping helper that does that for you”. There’s many looping helpers built-in, many in Python’s itertools module, and you can even invent your own (more on that in a few weeks).
If you’re feeling inspired to dive deeper into looping helpers, here’s some resources I’d recommend:
- My article How to Loop with Indexes in Python (6 minutes)
- Ned Batchelder’s talk/article Loop like a native: while, for, iterators, generators (30 minutes)
- The last part of DB’s talk Looping Like a Pro in Python (start from the beginning if you prefer to review the basics again)