Programming Tutorials

Iterate over a sequence in reverse order in python

By: Rajesh in Python Tutorials on 2012-04-07  

In Python, you can iterate over a sequence in reverse order using the reversed() function. The reversed() function takes a sequence as an argument and returns an iterator that yields the items of the sequence in reverse order. Here's an example:

my_list = [1, 2, 3, 4, 5]
for item in reversed(my_list):
print(item)

In this example, the reversed() function is used to create an iterator that yields the items of the my_list list in reverse order. The for loop then iterates over this iterator, printing each item to the console. The output of this code would be:

5
4
3
2
1

Note that the reversed() function returns an iterator, not a list. If you need the reversed sequence as a list, you can convert the iterator to a list using the list() function:

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)  # Output: [5, 4, 3, 2, 1]

In this example, the list() function is used to convert the iterator returned by reversed() to a list. The resulting list is stored in the reversed_list variable and printed to the console.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)