Python Range Reverse

Python range() function generates a sequence of integers. The sequence could be forward or reverse with respect to the values, when the step is positive or negative respectively.

In Python range() tutorial, we have gone through basic examples of range() function, where we have written Python range() function with positive steps. In this tutorial, we will learn how to take these steps in the backward or negative direction.

Python range() Reverse or Negative Steps

Python Range with Negative Steps

If we are taking steps in the backward direction, start argument should be greater than stop to generate any elements in the range object. And step should be a negative number.

In the following example, we shall generate a Python Range with sequence of integers starting from 10, decrementing in steps of 2 until 1.

Python Program

</>
Copy
start = 10
stop = 1
step = -2

for i in range(start, stop, step) :
    print(i)

Output

10
8
6
4
2

Let us try the same program with different start, stop and step values.

Python Program

</>
Copy
start = 100
stop = 0
step = -10

for i in range(start, stop, step) :
    print(i)

Output

100
90
80
70
60
50
40
30
20
10

Python Range with Negative Steps & Negative Numbers

In the following example, we shall generate a Python Range with sequence of negative integers starting from -1, decrementing in steps of 3 until -20. Please note that our start is greater than end, and step is negative.

Python Program

</>
Copy
start = -1
stop = -20
step = -3

for i in range(start, stop, step) :
    print(i)

Output

-1
-4
-7
-10
-13
-16
-19

Conclusion

In this Python Tutorial, we learned how to create a range with sequence of elements starting at a higher value and stopping at a lower value, by taking negative steps.