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.

In this tutorial, you will learn the syntax of reversed() function, and then its usage with the help of example programs.

Syntax

The syntax of reversed() function is

reversed(seq)

where

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

Examples

1. Reversed iterator on a 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 Code Copy

Output

o
l
l
e
H

2. 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 Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍