Unlike, JavaScript, C, Java, and many other programming languages we don't have traditional C-style for
loops.
Our for
loops in Python don't have indexes.
This small distinction makes for some big differences in the way we loop in Python.
We try to avoid using range to count, but we use enumerate when we need to count while looping over an iterable.
If you're thinking of "looping with indexes" the way you might in other languages, enumerate
is frequently the tool you'll reach for when you actually need indexes.
But we often don't need indexes.
One case where you might want indexes is to loop over multiple iterables at the same time. We actually don't do usually do that with indexes in Python! The zip function is the helper for looping over multiple iterables at once.
A big bonus to using zip
is that it works not only with indexable collections (sequences as we call them in Python: lists, tuples, strings, etc.) but for any iterable.
The below 10 minutes of screencasts include explanations of the word "iterable", an explanation of Python's for
loops, and a couple looping techniques.
If you prefer reading over watching, you can find the transcript for each screencast below each video.
for
loopfor
loops work in Python by Trey HunnerNeed to fill-in gaps in your Python skills?
Sign up for my Python newsletter where I share one of my favorite Python tips every week.
Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.