Python Range with Negative Step Value
Range with negative step creates a sequence of integers that start at a higher value and stop at a lower value.
In this tutorial, you will learn how to create a range with negative step value, with examples.
The syntax of range() function with the step parameter is
range(start, stop[, step])
where start and stop are the starting of the sequence and the ending of the sequence (stop not included), and the items are defined in given steps from start value.
For this specific scenario we are discussing, where step is a negative value, start must be greater than or equal to stop.
1. Range from 9 to 4 in steps of -2
In this example, we shall iterate over a range that starts at 9 and goes until 4 in steps of -2.
For example, in the following program, we define a range from 9 to 4 with a step value of -2.
2. Range from 12 to 1 in steps of -3
Now, let change the step value to -3 and observe the output.
12 9 6 3
In this tutorial of Python Examples, we learned how to create a range/sequence with descending values, using a negative step value in range() function.