How to reverse a range in Python

May 22, 2024#python

In Python, range() is a built-in function that generates an immutable zero-based sequence of numbers. It generates numbers on demand and does not store the entire sequence in memory, which makes it memory efficient, especially for large ranges.

# range(stop)
for i in range(5):
    print(i) # 0 1 2 3 4

# range(start, stop)
for i in range(2, 6):
    print(i) # 2 3 4 5

# range(start, stop, step)
for i in range(1, 10, 2):
    print(i) # 1 3 5 7 9

# creating a list from a range
numbers = list(range(5))
print(numbers) # [0, 1, 2, 3, 4]

To reverse a range created with the range() function in Python, you have a few options. The choice of method for reversing a range in Python depends on your specific needs and the size of the data you’re working with.

Using the reversed() function

The reversed() function takes a range (or any iterator supporting the sequence protocol) and returns a reversed-iterator object. You can use it in conjunction with the range() function to iterate over a sequence in reverse order.

for i in reversed(range(5)):

# 4 3 2 1 0

Using range() with negative step

If you want to use only the range() function to achieve the same result, you can specify all its parameters. The range(start, stop, step) syntax allows you to generate a list in reverse order.

for i in range(4, -1, -1):

# 4 3 2 1 0

Remember that the range() function produces integers from the start value (inclusive) up to the stop value (exclusive), using the specified step. In this case, we’re starting at 4 and counting down to -1 (inclusive) with a step of -1.

Using sorted() function

This sorted() function sorts an existing iterable (like a list, tuple, or another range) and returns a new list (<class 'list'>) containing the sorted elements. It creates a complete copy of the data in memory, which can be less efficient for very large datasets.

for i in sorted(range(5), reverse=True):

# 4 3 2 1 0

Using list slicing with a step of -1

List slicing in Python is a powerful technique for extracting portions of a list or sequence. It allows you to create a new list by specifying a range of indices from the original list.

The format for list slicing is [start:stop:step]. Negative indices count from the end of the list. -1 represents the last element, -2 the second-to-last, and so on.

for i in range(5)[::-1]:

# 4 3 2 1 0