Reverse iteration in python

In this article, we shall see how to perform reverse iteration with python. Let us also see what reverse iteration is, where, and when to use it?

Reverse iteration

Usually, when we iterate any iterator in python the values are iterated from the first index to the last. But what if we want to iterate the elements from the last index? Don’t worry python gives us a reversed() keyword which will take an iterator and returns the reversed elements.

Where and when to use it?

The reversed() object can be used in the following situations.

  1. When you do not want to reverse your original list.
  2. When you do not want to modify the original list.
  3. When you do not want to create a new list to store the reversed list for space complexity purposes.

Example

Let us look at this reversed() class with an example. I have the following list and I want to iterate them in a reversed fashion.

numbers = [1, 5, 10, 20, 100]

Then I can do something like this.

numbers = [1, 5, 10, 20, 100]

for number in reversed(numbers):
    print(number)

print(numbers)

The output of the above code is,

100
20
10
5
1
[1, 5, 10, 20, 100]

Note that the iteration alone is in reverse and that the original list is unmodified.

Conclusion

Hope this article is helpful. Leave your suggestions and comments below.

Happy coding !