runtime
23 / 250
lesson 23 Loops & Iteration · beginner

Count with range, number with enumerate

range() hands a for loop a run of whole numbers. enumerate() hands it each character together with its position.

You'll be able to
  • Count with range(stop), range(start, stop) and range(start, stop, step)
  • Remember that range stops before its stop number
  • Report where a character is with enumerate, counting positions from 0
The idea

Some loops don't walk a text at all: pay in 4 instalments, print a timetable every 15 minutes. range produces the whole numbers a for loop needs.

  • range(4) gives 0, 1, 2, 3. It starts at 0 and stops before 4, so it runs exactly 4 times.
  • range(1, 5) gives 1, 2, 3, 4: from the first number, stopping before the second.
  • range(0, 60, 15) gives 0, 15, 30, 45: the third number is the step. A negative step counts down: range(3, 0, -1) gives 3, 2, 1.

To count from 1 up to and including n, write range(1, n + 1).

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · An instalment plan
price = 240
months = 4
for month in range(1, months + 1):
    print("Month", month, "pay", price / months)
example-2.py · Half as many passes
months = 4
for month in range(months / 2):
    print(month)

Walking a text gives you each character, but not where it is. enumerate(text) gives both on every pass: the position, then the character. Two names go before in to receive them: for position, ch in enumerate(code):.

Positions start at 0: the first character is at position 0. That matters when a form tells someone where the problem in their input is.

example-3.py · Point at the space in a stock code
sku = "SPO 11681"
for position, ch in enumerate(sku):
    if ch == " ":
        print("Space at position", position)
print("Checked", sku)

When to use them: range when you know how many times to repeat, or you need the numbers themselves; enumerate when you need the position of characters in a text.

Mistakes to avoid: range(1, n) stops at n - 1, one pass short. Positions from enumerate start at 0, not 1. And range needs whole numbers, so use //, not /, to compute its arguments.

Review
  • range(stop), range(start, stop) and range(start, stop, step) give whole numbers and stop before stop.
  • range(1, n + 1) counts from 1 to n. Its arguments must be whole numbers.
  • enumerate(text) gives the position, from 0, and the character. Next: leaving a loop early with break, and skipping a pass with continue.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Count with range, number with enumerate — Loops & Iteration · Runtime