Learning LibraryCore Coding LibraryTeens

The range() function in Python: start, stop, step

"Months 1 through 12." "Every production run from 500 to 1,500, in steps of 250." Both are sequences of numbers, and range() generates either in one call.

The big idea

range(start, stop, step) produces whole numbers from start up to, but not including, stop, moving by step each time.

See it in code

1The basics

With one argument, range starts at 0. Wrap it in list() to see what it produces:

python
print(list(range(6)))
Run it. Six values, starting at zero:
[0, 1, 2, 3, 4, 5]

Six numbers, 0 through 5. The stop value itself is never included, which is why range(n) always gives exactly n values.

2A step further

Two arguments set the start as well. This is where the classic off-by-one lives:

python
print(list(range(1, 12)))
print(list(range(1, 13)))
Run it. Eleven months, then twelve:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

To include month 12, the stop has to be 13. A reliable check: the count of values is stop - start, so range(1, 13) holds 12.

3At Evergreen

A third argument is the step. Here it generates the production runs to compare, and each one is priced out in the loop:

python
cost = 14

for made in range(500, 1501, 250):
    print(f"Make {made:,} tees: ${made * cost:,} to produce")
Run it. What does each run cost to make?
Make 500 tees: $7,000 to produce
Make 750 tees: $10,500 to produce
Make 1,000 tees: $14,000 to produce
Make 1,250 tees: $17,500 to produce
Make 1,500 tees: $21,000 to produce

500, 750, 1,000, 1,250, 1,500. The stop was written as 1501 so that 1,500 itself is included.

The same idea, everywhere

range describes positions as well as quantities. range(0, len(dna), 3) walks a DNA strand three letters at a time, and range(len(prices)) visits every index of a list.

Try it yourself

Use a negative step: list(range(12, 0, -3)). Predict the output first, and note which end is excluded this time. Then generate every even month of the year.

The common mistake

Expecting the stop value to be included. range(500, 1500, 250) ends at 1,250. If the endpoint matters, push the stop one step past it.

What it unlocks

range drives most for loops. Two of them nest to cover every combination of two settings, and a range inside brackets becomes a list comprehension.

Want the simpler version? Read the Kids version →