The range() Function
range() produces a sequence of numbers to loop over — handy when you want to
repeat something a set number of times, or step through a run of values.
range(stop)
Counts from 0 up to but not including stop:
for i in range(5): print(i)This prints 0, 1, 2, 3 and 4, each on its own line: five iterations in total. The stop value 5 is not included.
range(start, stop)
Counts from start up to but not including stop:
for face in range(2, 7): print(face)range(2, 7) gives 2, 3, 4, 5, 6. The stop value 7 is never reached — a
neat way to step through the faces of a die that aren't 1.
The stop value is left out
This trips up nearly everyone at first: the number you pass as stop is
not included. To include a number, aim one past it. list() shows the
whole sequence at once:
print(list(range(1, 10)))print(list(range(1, 11)))The first one stops at 9. To get all the way to 10, the stop value has to
be 11.
Optional: choosing a step
A third argument, the step, sets how much the value changes each time:
for number in range(2, 9, 2): print(number)This prints 2, 4, 6 and 8. The stop value is still left out.
A negative step counts down. The stop must be smaller than the start:
for number in range(3, -1, -1): print(number)This prints 3, 2, 1 and 0. To end at 0, the stop is -1, one past it.
See also: For loops, The accumulator pattern.
Your turn
Add a loop that uses range() to print the numbers 1 to 5 — remember,
the stop value is left out.
1 2 3 4 5
# add a two-line loop using range()Advanced reading
- Range objects — measure, index and search a range without looping.
- enumerate() — get each position and item together, instead of
range(len(...)).