Positive and Negative Step Values
2 min read ·
The step value in
range() controls the direction and spacing of the generated sequence.Understanding how positive and negative steps work is essential for correct iteration.
Forward Iteration
A positive step value generates numbers in increasing order.
This is the default behavior when the step is omitted.
Values are generated from the start value and increase by the step value until the stop value is reached.
This generates even numbers in forward direction.
Reverse Iteration
A negative step value generates numbers in decreasing order.
For reverse iteration, the start value must be greater than the stop value.
The sequence decreases by one on each iteration.
Negative steps are commonly used for reverse loops and countdown logic.
Common Mistakes
Using a positive step with a decreasing range produces no output.
Using a negative step with an increasing range also produces no output.
Caution
Always match the step direction with the start and stop values.
Correct use of positive and negative step values ensures predictable sequence generation.