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.
In Python we have an idea of an iterable and our “for” loops are for looping over any iterable. Because we see the world from the perspective of “iterables”, we use lots of looping helpers.
Need to loop while counting upward? Use enumerate.
Need to loop over multiple iterables at the same time? Use zip.
Need to loop in the reverse direction? Use reversed.
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)
Deixe um comentário