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:

    python
    reversed(x)
    

Examples:

  1. 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 for loop.
    • Python Program:

      python
      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:
    • 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 for loop.
    • Python Program:

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

      9
      7
      5
      3
      1
      

Exercises:

  1. Reverse a Range of Numbers:
    • Write a program to create a range from 0 to 10 and print the numbers in reverse order.

      python
      for i in reversed(range(11)):
          print(i)
      
  2. 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.

      python
      for 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 a for loop. This is a useful technique for iterating over elements in reverse order in Python. Practice using the reversed() function to get comfortable with reversed iterators in your Python programs!