The reversed()
function returns a reverse iterator of the input iterable. It allows us to reverse the elements of an iterable object (list, string, tuple, etc.) without modifying the original iterable.
Syntax:
reversed(iterable)
The required iterable
parameter specifies the iterable object whose elements are to be reversed (e.g. a list, string, or tuple, etc). The iterable object should have the __reversed__()
method implemented .
The function returns an iterator objects containing the elements of the input iterable in reverse. We can then cast the returned iterator object into the relevant sequence type.
Reverse list items
Reverse tuple items
Reverse a string
In the above example we used the join()
method to join the reversed iterator back to a string.