Reversed Iterator for a Range
Introduction:
- In Python, you can use the
reversed()function to get a reversed iterator for a given range object. This allows you to iterate over the elements of the range in reverse order.
Syntax:
To get a reversed iterator for a range
x, use:pythonreversed(x)
Examples:
- Reversed Iterator for a Range (1, 5):
- This example shows how to get a reversed iterator for the range from 1 to 5 and iterate over it using a
forloop. Python Program:
pythonx = range(1, 5) for item in reversed(x): print(item)Output:
4 3 2 1
- This example shows how to get a reversed iterator for the range from 1 to 5 and iterate over it using a
- Reversed Iterator for Range (1, 10) with step=2:
- This example shows how to get a reversed iterator for a range from 1 to 10 with a step of 2 and iterate over it using a
forloop. Python Program:
pythonx = range(1, 10, 2) for item in reversed(x): print(item)Output:
9 7 5 3 1
- This example shows how to get a reversed iterator for a range from 1 to 10 with a step of 2 and iterate over it using a
Exercises:
- Reverse a Range of Numbers:
Write a program to create a range from 0 to 10 and print the numbers in reverse order.
pythonfor i in reversed(range(11)): print(i)
- Reverse a Range with a Step:
Write a program to create a range from 5 to 20 with a step of 3 and print the numbers in reverse order.
pythonfor i in reversed(range(5, 21, 3)): print(i)
Summary:
- In this tutorial, we learned how to use the
reversed()function to get a reversed iterator for a range object and iterate over it using aforloop. This is a useful technique for iterating over elements in reverse order in Python. Practice using thereversed()function to get comfortable with reversed iterators in your Python programs!