Python Range Reverse, For Loop Reverse Range
In this tutorial, we will learn how to use the Python
range function in reverse order and use
for loops in reverse range.
Usually, we use the
range function in a
for loop as follows (for example, to generate a list of numbers from 1 to 10):
for num in range(1, 11): print(num)
To do the same thing in reverse order, we have to use the third argument (stepping)
For example, to generate a list of numbers from
10 in the first field,
zero(0) in the second field, and
-1 in the third field, as shown in the following code block:
for num in range(10, 0, -1): print(num)
for loop above will print the following:
Let’s look at another example that shows using Python range Function in backwards
for num in range(10, 0, -2): print(num)
This time we used
-2 in the third argument. This generates a sequence of numbers in steps of two.
Following is another code example that generates a sequence of numbers in reverse order in steps of three:
for num in range(10, 0, -3): print(num)
The syntax of the Python
range function is
range(start, stop, step_count). It generates a list of numbers from the start number up to, but not including the stop number.