Loop through a Range backwards in Python

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Loop through a Range backwards in Python #

Use the reversed() function to loop through a range backwards, e.g. for i in reversed(range(1, 6)):. The reversed() function takes an iterator, such as a range, reverses it and returns the result.

main.py
# ✅ loop through a range backwards using reversed() for i in reversed(range(1, 6)): print(i) # 👉️ 5 4 3 2 1 # ------------------------------------ # ✅ loop through a range backwards using negative step for i in range(5, 0, -1): print(i) # 👉️ 5 4 3 2 1

The first example uses the reversed() function to reverse a range object.

The reversed function takes an iterator, reverses it and returns the result.

main.py
my_range = reversed(range(1, 11)) my_list = list(my_range) print(my_list) # 👉️ [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

We used 1 for the start value and 6 for the stop value.

main.py
for i in reversed(range(1, 6)): print(i) # 👉️ 5 4 3 2 1
Notice that the start value is inclusive and the stop value is exclusive (up to, but not including).

Alternatively, you can use a negative step.

Loop through a Range backwards using a negative step #

Use a negative step to loop through a range backwards, e.g. for i in range(5, 0, -1):. The range() class can be passed a step of -1 to create a range object that counts backwards from a specified number.

main.py
for i in range(5, 0, -1): print(i) # 👉️ 5 4 3 2 1

We used a negative step to iterate over the range in reverse order.

We used 5 for the start value and 0 for the stop value, so the range starts at 5 and goes up to, but not including 0.

When a negative step value is specified, the range counts backwards from the start value.

You might also see examples online that use slicing to reverse the range.

main.py
# 👇️ range(5, 0, -1) print(range(1, 6)[::-1]) for i in range(1, 6)[::-1]: print(i) # 👉️ 5 4 3 2 1

The syntax for slicing is my_sequence[start:stop:step].

We omitted the start and stop values and only specified a negative step to reverse the range.

Which approach you pick is a matter of personal preference. I'd go with using the reversed() function as I find it more readable and intuitive.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.