Python reversed()

Python reversed() builtin function takes a sequence and returns a new sequence with elements of the given sequence reversed.

In this tutorial, we will learn about the syntax of Python reversed() function, and learn how to use this function with the help of examples.

Syntax

The syntax of reversed() function is

reversed(seq)

where

ParameterRequired/OptionalDescription
seqRequiredA python sequence like list, tuple, string, or any user defined object that implements __reversed__() method.

Returns

The function returns the object of type as that of the given argument.

Example

In this example, we will take a list object with integers as elements, and pass it as argument to reversed() function. The function should return a new list with objects of given list reversed.

Python Program

myList = [2, 4, 6, 8]
result = reversed(myList)
print(list(result))
Try Online

Output

[8, 6, 4, 2]

For input type of list, reversed() function returns object of type list_reverseiterator. We may convert it to list using list() builtin function.

reversed(tuple)

In this example, we will reverse a tuple object using reversed() function.

Python Program

myTuple = (2, 4, 6, 8)
result = reversed(myTuple)
print(tuple(result))
Try Online

Output

(8, 6, 4, 2)

For argument type of tuple, reversed() function returns object of type reversed. We may convert it to tuple using tuple() builtin function.

Conclusion

In this Python Tutorial, we have learnt the syntax of Python reversed() builtin function, and also learned how to use this function, with the help of Python example programs.