How to Reverse a Range in Python?

Estimated read time 1 min read

In Python, you can reverse a range by using the reversed() function. However, the reversed() function returns a reversed iterator, so you need to convert it back to a list if you want to print or use the reversed range as a list. Here’s an example:

my_range = range(1, 6)  # Range: 1, 2, 3, 4, 5

reversed_range = list(reversed(my_range))

print(reversed_range)

Output:

[5, 4, 3, 2, 1]

In this example, we have a range my_range that starts from 1 and ends at 6 (exclusive). We pass my_range to the reversed() function, which returns a reversed iterator. Then, we convert the reversed iterator back to a list using the list() function and assign it to reversed_range. Finally, we print reversed_range, which gives us the reversed range [5, 4, 3, 2, 1].

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply