Python reversed Function with Examples

The Python reversed function provides an iterator that yields the elements of a specified sequence in reverse order.

Python reversed Function Syntax

It has the following syntax:

Example

reversed(sequence)

Parameters

  • sequence: This refers to a sequence that requires reversal.
  • Return

It provides the iterator that traverses the specified sequence in reverse order.

Python reversed Function Example

The preceding example illustrates how the reversed function operates on various sequences, including strings, tuples, lists, and ranges.

Example

# for string

String = 'Python'

print(list(reversed(String)))

# for tuple

Tuple = ('J', 'a', 'v', 'a')

print(list(reversed(Tuple)))

# for range

Range = range(8, 12)

print(list(reversed(Range)))

# for list

List = [1, 2, 7, 5]

print(list(reversed(List)))

Output:

Output

['a', 'v', 'a', 'J']

['a', 'v', 'a', 'J']

[11, 10, 9, 8]

[5, 7, 2, 1]

Explanation:

In the example provided above, we utilized a string containing the value " Java ", and it outputs the string in a reversed format.

In the subsequent scenario, we utilize a tuple that contains identical values, and it outputs the tuple with its elements displayed in reverse order.

In the third scenario, we have selected a range encompassing a series of numeric values, and it outputs the values of this range in reverse order.

In the fourth scenario, we have utilized a collection containing various numeric values, and it outputs the list in a reversed order.

Input Required

This code uses input(). Please provide values below: