The most efficient way to reverse a range object in Python is to use either the “slicing” or the “reversed()” function.
Here is the image that describes the normal range vs the reverse range:When we talk about range, we are not talking about the list or any other data structure. We are simply talking about a range object. The range object and list object are fundamentally different types.
The range is a dedicated type representing an immutable sequence of numbers for looping. The list is of type list, which acts as a container to store every single element explicitly in memory.
Efficient method: Slicing ([::-1])
The range object supports slicing, which allows us to create a reverse range directly by specifying [::-1] as the slice. This can be the fastest approach because its time and space complexity is O(1).
Why is it so efficient? Because slicing is a highly optimized operation in CPython for tasks like reversing a sequence.
range_obj = range(1, 6) for i in range_obj: print(i) # 1 # 2 # 3 # 4 # 5 reversed_range = range_obj[::-1] for i in reversed_range: print(i) # 5 # 4 # 3 # 2 # 1
The above code shows that the output is a reversed sequence of numbers.
Range with Step
The range() function provides a step argument to add steps to your sequence. Using [::-1], we can reverse that range, too.
range_obj = range(2, 11, 2) for i in range_obj: print(i) # 2 # 4 # 6 # 8 # 10 reversed_range = range_obj[::-1] for i in reversed_range: print(i) # 10 # 8 # 6 # 4 # 2
Negative Step Range
If you pass the step negative, it will start iterating from the end of the range. And then if you reverse the already reversed range, you will have a normal range.
range_obj = range(5, 0, -1) for i in range_obj: print(i) # 5 # 4 # 3 # 2 # 1 reversed_range = range_obj[::-1] for i in reversed_range: print(i) # 1 # 2 # 3 # 4 # 5
Empty range
If you are using an empty range, the reverse range will be empty too!
range_obj = range(5, 1) for i in range_obj: print(i) # Empty range object reversed_range = range_obj[::-1] for i in reversed_range: print(i) # Empty reverse range
Using reversed()
The reversed() function returns an iterator that accesses the range in reverse order and does not create an intermediate list, making it an efficient choice. The time and space complexity is O(1).
range_obj = range(1, 6) for i in range_obj: print(i) # 1 # 2 # 3 # 4 # 5 reversed_range = reversed(range_obj) print(list(reversed_range)) # [5, 4, 3, 2, 1]
You can see that we get the output as a list, not an iterator, because we passed an iterator to the list() constructor.
Using sorted (Not recommended)
The sorted() function converts a range to a list, sorts the list in reverse, and returns a new list. However, this approach is inefficient because it has O(n) time and space complexity.
range_obj = range(1, 6) for i in range_obj: print(i) # 1 # 2 # 3 # 4 # 5 reversed_range = sorted(range_obj, reverse=True) print(list(reversed_range)) # [5, 4, 3, 2, 1]
That’s all!