Skip to content
For Loops
step 1/8

Reading — step 1 of 8

Learn

~3 min readLoops and Iteration

Repetition is what makes computers powerful. A human gets bored adding a thousand numbers; a computer does it in microseconds without complaint. The for loop is Python's workhorse for repetition — you reach for it when you know what you're iterating over: a range of numbers, the characters in a string, the items in a list.

The shape of a for loop

python

The header reads as: "For each i IN range(1, 6), run the indented body." Python repeatedly assigns each value from the iterable to the loop variable and runs the body.

Four pieces:

  1. The keyword for.
  2. A loop variable (i here, but use whatever name describes the value).
  3. The keyword in followed by something iterable.
  4. A colon, and an indented block.

range() — three forms

range() is the most common iterable in Python loops. It generates a sequence of integers without storing them all in memory. It has three forms:

python

The stop value is exclusiverange(1, 6) goes 1 through 5, NOT through 6. This trips up almost every beginner. The convention matches list slicing and is consistent across Python.

Want 1 through 10? Use range(1, 11). Want 1 through N? Use range(1, N + 1).

Iterating over strings, lists, and other iterables

A for loop works on any iterable, not just range:

python

Counting with enumerate

A classic mistake is reaching for range(len(...)) to get indices:

python

enumerate(iterable) yields (index, value) pairs. Use it whenever you need both. To start at 1 instead of 0: enumerate(names, start=1).

Pairing two iterables with zip

Sometimes you need to walk two lists in lockstep:

python

zip stops at the shortest sequence. For unequal lengths where you want to pad, use itertools.zip_longest.

Accumulating a result

A huge fraction of for-loops are computing one value from many:

python

The pattern: an accumulator variable initialized BEFORE the loop, updated INSIDE.

Common mistakes

  • Off-by-one errors: range(1, N) gives 1 through N-1, not 1 through N. For 1 through N, use range(1, N + 1).
  • Modifying a list while iterating it: for x in items: if x == 0: items.remove(x) skips elements unpredictably. Iterate over a copy: for x in items[:]: or build a new list.
  • Forgetting range for indices: for i in numbers: gives you the values, not the indices.
  • range(len(x)) when you really wanted enumerate(x) — works but verbose.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…