Here are three ways to reverse a range in Python:
- Using reversed() with range()
- Using range() with a Negative Step
- Using sorted() function
Method 1: Using reversed() with range()
The reversed() function returns an iterator that accesses the given sequence in the reverse order.
Visual Representation
Example
# Loop through a reversed range from 0(default start value) to 4(5 is the end value but not included)
for i in reversed(range(5)):
print(i)
Output
4
3
2
1
0
Method 2: Using range() with a Negative Step
Follow the below steps:
- Your start should be the maximum number in your range.
- Your stop must be a minimum number – 1 in your range.
- You need to decrement by 1 (use a step of -1) to get the exact reverse of your list.
When the step argument is negative, you iterate through a sequence of decreasing numbers, effectively decrementing. This allows you to traverse the numbers in reverse order.
Visual Representation
Example
for i in range(10, 5, -1): # Starts at 10, ends at 6, steps backwards by 1
print(f"{i}")
Output
10
9
8
7
6
Method 3: Using sorted() function
The sorted() function returns a new list containing all items from the iterable in ascending order by default, but you can reverse the order by setting reverse=True.
Visual Representation
Example
new_range = range(4)
reversed_list = sorted(new_range, reverse=True)
print(reversed_list)
Output
[3, 2, 1, 0]