Python reversed() Function



The Python reversed() function is a built-in function used to return an iterator object which allows us to access the specified sequence in reverse order. This function is commonly used in the situation where we want to iterate over the elements of a sequence in reverse, without modifying the original sequence.

Note that the reversed() function only works with those sequence or collections that supports indexing, such as lists, tuples, and strings. Since sets and dictionaries are unordered collections, this function does not support them.

Syntax

The syntax of the Python reversed() function is as follows −

reversed(seqObj)

Parameters

The Python reversed() function accepts a single parameter −

  • seqObj − It represents an sequence object such as a list, string, or tuple.

Return Value

The Python reversed() function returns an iterator object.

Examples

Not, let's see some examples of reversed() function −

Example 1

The following example shows the usage of Python reversed() function on a built-in sequence object. Here, we are creating and reversing a list.

numericList = [12, 14, 18, 20, 10, 5]
revIterator = reversed(numericList)
# Converting reverse iterator to list
revList = list(revIterator)
print("Displaying list in reverse order:")
print(revList)

When we run above program, it produces following result −

Displaying list in reverse order:
[5, 10, 20, 18, 14, 12]

Example 2

Since the string is also a sequence object, the reversed() can be apply to it. If we reverse a string, this function will return its characters in reverse order as shown in the below Python code.

orgnlStr = "TutorialsPoint"
print("Before Reversing:", orgnlStr)
reversedStr = ''.join(reversed(orgnlStr))
print("After Reversing:", reversedStr) 

Following is an output of the above code −

Before Reversing: TutorialsPoint
After Reversing: tnioPslairotuT

Example 3

The code below demonstrates how to use the reversed() function with the for loop to iterate and print the items of sequence objects in reverse order.

numericList = [12, 14, 18, 20, 10, 5]
print("Displaying list in reverse order:")
for revList in reversed(numericList):
   print(revList)

Output of the above code is as follows −

Displaying list in reverse order:
5
10
20
18
14
12

Example 4

In the code below a range object is defined using range() function. Then we reverse it with the help of reversed() function. We are able to reverse this object because it is an immutable sequence type.

rangeObject = range(11, 20, 2)
print("Displaying range object item in reverse order:")
for revList in reversed(rangeObject):
   print(revList)

Following is an output of the above code −

Displaying range object item in reverse order:
19
17
15
13
11
python_built_in_functions.htm
Advertisements