Python reversed()
is built-in function that returns a reverse iterator of a given sequence. In simple words, this function when applied to a sequence returns an iterator that generates the elements of the sequence in the reverse order.
reversed(sequence)
reversed()
function takes only one parameter as an argument.
This sequence must be an object which has a __reversed__()
method or supports the sequence protocol (the __len__()
method and the __getitem__()
method).
>>> #reversed with lists
>>> py_list = [1,2,3,4,5]
>>> reversed_list = reversed(py_list)
>>> print(list(reversed_list))
[5, 4, 3, 2, 1]
>>> #with tuples
>>> py_tuple = ('P','Y','T','H','O','N')
>>> reversed_tuple = reversed (py_tuple)
>>> print(tuple(reversed_tuple))
('N', 'O', 'H', 'T', 'Y', 'P')
>>> #with strings
>>> py_str = 'PYTHON'
>>> reversed_string = reversed(py_str)
>>> print(list(reversed_string))
['N', 'O', 'H', 'T', 'Y', 'P']
That is how reversed()
function works with different sequences like lists, tuples, strings and others. Now let’s see how reversed()
works with Python for loop.
>>> #reversed() with for loop
>>> for x in reversed([1,2,3]):
print x
3
2
1
For custom objects, we need to use and edit the inbuilt method __reversed__()
which works behind the scene in reversed()
function.
#reversed() for custom objects
class Example:
x = [1,2,3]
def __reversed__(self):
return reversed(self.x)
obj = Example()
print(list(reversed(obj)))
The output of above script will be:
[3, 2, 1]