In this lesson, you will learn how to count backward through a numeric sequence by using a negative step value in the range() function.
Stepping Backwards
So far, you have used range() to count upward, such as range(0, 5), which gives you 0, 1, 2, 3, 4. You also learned how to use a "step" argument to skip numbers (like range(0, 10, 2)). Today, we are going to flip that logic entirely.
To iterate in reverse, we use the same range(start, stop, step) structure, but we provide a negative integer for the step argument. When the step is negative, Python counts down from the start to the stop value.
How It Works
Imagine you are building a countdown timer. You want to start at 5 and finish just before 0. Here is how you write that:
# Counting down from 5 to 1
for number in range(5, 0, -1):
print(number)
In this code:
5is your starting point.0is your stopping point (remember: the stop value is exclusive, so the loop will stop before reaching 0).-1is the instruction to decrease the value by 1 in each iteration.
If you don't provide a negative step while your start value is higher than your stop value, Python will assume you want an empty sequence and the loop simply won't run. For example, range(5, 0) will produce nothing because Python defaults to a step of 1, and it cannot count from 5 to 0 by adding 1s.
By mastering the negative step, you gain the ability to process data from the end to the beginning, which is incredibly useful for tasks like reversing a list or creating countdown effects in your programs.
Key Takeaway: To count backward, set the range() start higher than the stop value and provide a negative integer as the third argument to define the decrement.