Python · Small experiments
Why does range() stop before the stop?
Python range(start, stop, step) produces integers beginning at start. With a positive step, it keeps values below stop. With a negative step, it keeps values above stop. The stop value is excluded.
list(range(1, 6, 1))5 values. The stop value 6 is excluded.
This explorer models integer ranges. Use the full Python playground to run your own program.
Read the arguments in order
range(5) uses a start of 0 and a step of 1, giving 0, 1, 2, 3, 4. range(1, 5) gives 1, 2, 3, 4. range(1, 6, 2) gives 1, 3, 5. A range can be iterated directly; list(range(...)) makes its values visible for a small example.
Count backward with a negative step
range(5, 0, -1) gives 5, 4, 3, 2, 1. The stopping comparison reverses because each new value is smaller. If the step points away from the stop, the range is empty: range(1, 5, -1) has no values.
Watch two common mistakes
A step of 0 is invalid because the sequence would never move. An excluded stop also causes off-by-one mistakes when you expect a loop to include its upper endpoint.
- Write the first value and expected last value before running.
- Use range(len(items)) for valid zero-based indexes when you actually need indexes.
- When you only need the items, iterate over the collection directly.
Use a small experiment to debug
Change only one argument at a time. Predict the next output, then run the program and compare. A short loop makes the boundary easier to see than a larger program with several changing variables.
Check the reference
Use these original references to check the definitions behind this guide.