Part 3 of 6 · Chapter 2 of 4

Doing Something More Than Once

Looping in Python means iterating over the thing itself, not counting up to its length and hoping you stop in time. Step through a collection one item at a time and watch the loop variable outlive the loop that created it.

Beginner9 min read

Looping in Python means iterating over the thing itself, not counting up to its length and hoping you stop in time. Step through a collection one item at a time and watch the loop variable outlive the loop that created it.

Iterating over the thing, not an index into it

Many languages loop by counting: start at 0, stop before the length, index in each time. Python's for hands you the items directly.

Terminal
$ >>> for fruit in ["apple", "banana", "cherry"]:$ ...     print(fruit)$ apple$ banana$ cherry

fruit is not an index — it is each item, in turn. If you need the position too, enumerate() hands you both without you tracking a counter yourself: for i, fruit in enumerate(fruits):.

for number in numbers:
1245723

Current iteration: number = 12

total = 0

While: repeating until something changes

Use for when you already have the collection to iterate over. Use while when you are repeating until a condition changes, and you do not know in advance how many times that will take.

Terminal
$ >>> total = 0$ >>> while total < 10:$ ...     total += 3$ >>> total$ 12

The loop variable is still there after the loop ends

Unlike some languages, Python does not create a fresh scope for a loop body. The variable you loop with is an ordinary name in the surrounding function or module, and it keeps whatever value it last held once the loop finishes.

Terminal
$ >>> for fruit in ["apple", "banana", "cherry"]:$ ...     pass$ >>> fruit$ 'cherry'

Key takeaways

  • for iterates over the items directly. Use enumerate() if you also need the position.
  • Use while when you are repeating until a condition changes, not counting through a known collection.
  • A while loop whose condition never becomes false never stops — check that the body moves it toward finishing.
  • A loop variable is not deleted when the loop ends. It keeps the last value it was assigned.