Python range(): Start, Stop and Step
Core idea
range(stop) starts at zero; range(start, stop) sets the starting integer; range(start, stop, step) sets the signed increment. The stop value is excluded. A range is a sequence object representing integers without storing a list of all its items. Use it with for to repeat a known number of times.
The default start is 0 and the default step is 1. Four values appear; 4 is not included.
Use positive and negative steps
for n in range(2, 9, 3): print(n)print("Back")for n in range(5, 0, -2): print(n)The first sequence increases by 3. The second decreases by 2 and stops before reaching or crossing zero.
Zero step: intentional error
A zero step is invalid; Python raises ValueError. An incompatible nonzero direction, such as range(5, 1, 1), instead produces an empty sequence.
Common mistake
For integers 1 through 5, write range(1, 6), not range(1, 5). The end is a boundary, not the last promised item.
Practice
Print the even integers from 4 through 12, then print them in reverse using a negative step.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Range boundaries and steps
Check your understanding of range.
What is printed?
for n in range(3): print(n)What is printed?
for n in range(6, 0, -2): print(n)What happens?
range(1, 4, 0)Which range produces 3, 5, 7?