Python reversed() built-in function
From the Python 3 documentation
Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).
Introduction
The reversed()
function returns a reverse iterator. This means it can be used to loop over a sequence (like a list, tuple, or string) in reverse order. It doesn’t modify the original sequence but instead provides a new iterator that yields items from end to start.
Examples
To get a reversed list, you can convert the iterator to a list:
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list) # Output: [5, 4, 3, 2, 1]
You can also iterate over it directly in a for
loop:
for char in reversed("hello"):
print(char)
# Output:
# o
# l
# l
# e
# h
Here is another example demonstrating the iterator behavior:
>>> i = reversed([1, 2, 3])
>>> next(i)
# 3
>>> next(i)
# 2
>>> next(i)
# 1