Python reversed()

The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.

Example


reversed() Syntax

The syntax of reversed() is:

reversed(sequence_object)

reversed() Parameter

The reversed() method takes a single parameter:

  • sequence_object - an indexable object to be reversed (can be a tuple, string, list, range, etc.)

Note: Since we can't index objects such as a set and a dictionary, they are not considered sequence objects.


reversed() Return Value

The reversed() method returns:

  • a reversed list of items present in a sequence object

Example 1: Python reversed() with Built-In Sequence Objects

Output

['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

In the above example, we have used the reversed() method with objects like tuple, range and a list.

When using the reversed() method with these objects, we need to use the list() method to convert the output from the reversed() method to a list.


Example 2: reversed() with Custom Objects

Output

['u', 'o', 'i', 'e', 'a']

In the above example, we have used the reversed() method with a custom object v of the Vowels class.

Here, the method returns the reverse order of the sequence in the vowels list.


Recommended Readings: