range()
Produces a sequence of whole numbers from a start to an end, with an optional step, mostly used to repeat a for loop a set number of times.
range(stop)
range(start, stop, step=1)range() gives you a row of whole numbers. range(5) means 0, 1, 2, 3, 4; range(1, 6) means 1 to 5; range(0, 20, 5) means 0, 5, 10, 15.
Its main job is to drive a for loop loop: for i in range(10): repeats the loop ten times. It is also handy for building lists of numbers and for counting backwards.
The end number is never included. This feels odd at first, but it means range(n) has exactly n numbers and range(len(items)) matches the positions of a list. A range is also lazy: it does not store its numbers, it works each one out when asked, so range(1_000_000_000) takes almost no memory.
Parameters
| Parameter | What it is |
|---|---|
startoptional, default 0 | The first number. Only allowed when you also give stop. |
stoprequired | Where to stop. This number itself is not included. |
stepoptional, default 1 | How much to add each time. Use a negative step to count down. It cannot be 0. |
Return value
A range object: a sequence you can loop over, index, slice and measure with len(). Wrap it in list() to see all the numbers.
Examples
1The three forms
print(list(range(5)))
print(list(range(2, 7)))
print(list(range(0, 20, 5)))[0, 1, 2, 3, 4] [2, 3, 4, 5, 6] [0, 5, 10, 15]
2Repeat something a fixed number of times
for attempt in range(1, 4):
print("Attempt", attempt, "of 3")Attempt 1 of 3 Attempt 2 of 3 Attempt 3 of 3
3Count down with a negative step
for n in range(10, 0, -3):
print(n)
print("Lift off!")10 7 4 1 Lift off!
With a negative step the range stops before it reaches stop from above, so 0 is not printed.
4A range is lazy but still knows a lot
r = range(0, 100, 7)
print(r)
print(len(r))
print(r[3], r[-1])
print(49 in r, 50 in r)range(0, 100, 7) 15 21 98 True False
Printing a range does not list its numbers. Yet you can still ask its length, pick a position and test in, all without building a list.
5Build a price table
unit_price = 2.40
for qty in range(1, 6):
print(f"{qty} x {unit_price:.2f} = {qty * unit_price:.2f}")1 x 2.40 = 2.40 2 x 2.40 = 4.80 3 x 2.40 = 7.20 4 x 2.40 = 9.60 5 x 2.40 = 12.00
Common mistakes
Expecting the end number to be included
range(1, 10) stops at 9. To include 10, the end must be one more: range(1, 11).
print(list(range(1, 10))[-1])
print(list(range(1, 11))[-1])9 10
Using decimal numbers
range() only accepts whole numbers. For steps like 0.5, loop over whole numbers and divide.
try:
range(0, 2, 0.5)
except TypeError:
print("TypeError: range() needs whole numbers")
print([n / 2 for n in range(0, 4)])TypeError: range() needs whole numbers [0.0, 0.5, 1.0, 1.5]
Using range(len(...)) when you only need the items
for i in range(len(names)): print(names[i]) works, but for name in names: is shorter and clearer. If you need the position as well, use enumerate().
Questions people ask
How do I make a list of numbers from 1 to 10?
list(range(1, 11)). The end is not included, so use 11.
How do I loop backwards with range?
Give a negative step: range(10, 0, -1) gives 10 down to 1. Or use reversed(): reversed(range(1, 11)).
Why does print(range(5)) not show the numbers?
A range does not store its numbers, so it prints as range(0, 5). Use print(list(range(5))) to see them.
What is the difference between range and xrange?
xrange only existed in Python 2. Python 3's range already works the lazy way xrange did.