reversed() Builtin Function

Python reversed()

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.

Syntax

The syntax of reversed() function is

reversed(seq)

where

seqA Python sequence. For example a string, list, range, tuple, etc.

Examples

Reversed Iterator on String

In this example, we will take a string, and get the reversed iterator on this string using reversed() builtin function.

Python Program

x = 'Hello'
result = reversed(x)
for ch in result:
    print(ch)
Run

Output

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.

Python Program

x = [2, 4, 6, 8]
result = reversed(x)
for item in result:
    print(item)
Run

Output

8
6
4
2

Summary

In this tutorial of Python Examples, we learned the syntax of reversed() builtin function and how to use it, with the help of examples.