How to reverse a range in Python (with examples)
How to reverse a range in Python
Sometimes you need to reverse a range in Python to iterate over a list of items in reverse order. This quick guide explores two popular methods of reversing ranges (or any iterator) in Python.
Before we start, let’s quickly review Python’s
range() function. A range object in Python is a sequence of numbers you can use with a
for loop to repeat a set of instructions a specific number of times.
range() function makes it super easy to generate range objects. The range function accepts three parameters:
With these parameters, you can define where the sequence begins and ends. And thanks to the
step parameter, you can even choose how big the difference will be between one number and the next.
For instance, to generate a range from
10 with a step of
2, you call the range function like so:
items = range(0, 10, 2) print(items) # output: range(0, 10, 2) # Convert them into a list print(list(items)) # output: [0, 2, 4, 6, 8]
Using ranges with
for loops is straightforward:
for i in range(0, 10, 2): print(i)
The above code generates the following output:
0 2 4 6 8
Reverse a range using reversed()
Alright, now let's see how we can reverse a range in Python to iterate over it in reverse order.
Luckily, Python makes it easy to do this with the
You can use
reversed() function in conjunction with the
range() function in
for loops to iterate over a sequence in reverse order:
for i in reversed(range(0, 10, 2)): print(i)
And the output would be:
8 6 4 2 0
You can also use the
reversed() function with a list. In this case, the returned value will be a
my_list = [1, 2, 3, 4, 5] for i in reversed(my_list): print(i)
Generate a reversed range
You can also use the
range() function to generate a sequence of numbers in reverse order.
In this case, the
start argument is the highest number in the range, and the
stop parameter is the lowest. Obviously, the
step parameter should be a negative value like
To create a range from
0 with a step of
2, we can do it like so:
for i in range(10, 0, -2): print(i)
The output would be:
And to create a reversed list with negative numbers:
for i in range(-10, 0, 2): print(i)
-10 -8 -6 -4 -2
Alright, I think that does it! I hope you found this quick guide helpful.
Thanks for reading
If you read this far, you can tweet to the author to show them you care. Tweet a Thanks
Never miss a guide like this!
Join the DWD mailing list for your weekly dose of knowledge! This mailing list is for doers and thinkers. If you're a curious person, you might find it useful, just as 2,000 other devs do!
Disclaimer: This post might contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.