Python reversed() function takes a sequence as argument and returns a reversed iterator for the sequence. Reversed iterator meaning, when we iterate over the returned object, we get the elements of the sequence in reversed order.
The syntax of reversed() function is
|seq||A Python sequence. For example a string, list, range, tuple, etc.|
Reversed Iterator on String
In this example, we will take a string, and get the reversed iterator on this string using reversed() builtin function.
x = 'Hello' result = reversed(x) for ch in result: print(ch)
o l l e H
Reversed Iterator on a List
In this example, we will take a list of numbers, and get the reversed iterator on this list using reversed() builtin function. We use for loop to iterate over the resulting object, and print the elements.
x = [2, 4, 6, 8] result = reversed(x) for item in result: print(item)
8 6 4 2
In this tutorial of Python Examples, we learned the syntax of reversed() builtin function and how to use it, with the help of examples.