89DEVs

Python: How to reverse range?

How to reverse range in Python? Use the step argument of the range() function with a negative value.

Syntax of range() function: range(start, stop, step)

To create a range from 3 to 1 use range(3, 0, -1)


for n in range(3, 0, -1):
   print(n)



3
2
1


To create a range of even numbers we can use the range function with step -2.


for n in range(6, 0, -2):
   print(n)



6
4
2