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.
forloops work in Python by Trey Hunner
Hello friendly web visitor! 👋
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing. In the case of Python that means writing Python code. If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well. You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.