Python ยท Chapter 14 of 45

Python For Loop

`for` iterates over any sequence: list, tuple, string, range, dict keys, or any iterable.

Use `range(n)` to loop a fixed number of times.

range() variants

`range(stop)`, `range(start, stop)`, `range(start, stop, step)`. Stop is exclusive.

Looping with index

Use `enumerate(seq)` when you need both the index and the value.

Example 1 (python)
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)
Output
apple
banana
cherry

Iterates over each item in the list.

Example 2 (python)
for i, name in enumerate(["Ana", "Ben"], start=1):
    print(i, name)
Output
1 Ana
2 Ben

enumerate gives (index, value) pairs.

Key points

  • Iterates over any iterable.
  • `range(n)` produces 0 to n-1.
  • Use `enumerate()` for (index, value).
  • Use `zip()` to loop over multiple sequences in parallel.
๐Ÿ’ก Note: Never modify a list while iterating over it โ€” copy it first: `for x in mylist[:]`.

๐Ÿ“ Quick Quiz

1. `range(5)` produces:

2. Which returns (index, value) pairs?

3. for loop iterates over: