Reversed Iterator for a Range


Python - Reversed Iterator for a Range

To get a reversed iterator for a given range object, pass the range object as argument to reversed() function.

The following is an expression that returns reversed iterator for range x.

reversed(x)

Examples

1. Reversed Iterator for a Range (1, 5)

In this example, we take a range from 1 to 5, get a reversed iterator for this range, and iterate over the returned object using for loop.

Python Program

x = range(1, 5)
for item in reversed(x):
    print(item)

Output

4
3
2
1

2. Reversed Iterator for Range (1, 10) with step=2

Let us take a range with step=2, and get reversed iterator for this range.

Python Program

x = range(1, 10, 2)
for item in reversed(x):
    print(item)

Output

9
7
5
3
1

Summary

In this tutorial of Python Examples, we learned how to get the reversed iterator for a given range object using reversed() builtin function, with the help of well detailed example programs.