Looping, the Python way

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.

Screencasts (including transcripts)

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.

  1. What is an iterable?
  2. Writing a for loop
  3. Looping with indexes (looping while counting)
  4. Looping over multiple iterables at the same time

Recommended Resources