Python reversed() Function

The reversed() function in Python returns the reversed iterator object or the iterator of a given sequence such as list, tuple, string etc. For example:

a = [32, 34, 56, 76]
b = reversed(a)
for x in b:
    print(x, end=" ")

Following is the output produced by this Python program, demonstrating the reversed() function:

76 56 34 32 

Python reversed() Function Syntax

The syntax of reversed() function is:

reversed(sequence)

Python reversed() Function Example

Here is an example example that uses the reversed() function to get the reverse iterator of a sequence:

print("Enter the size: ", end="")
n = int(input())
print("Enter", n, "elements: ", end="")
seq = []
for i in range(n):
    val = input()
    seq.append(val)

print("\nThe original sequence is:")
for x in seq:
    print(x, end=" ")

seq = reversed(seq)
print("\nThe reversed sequence is:")
for x in seq:
    print(x, end=" ")

The snapshot given below shows the sample run of above program, with user input 5 as size, and 50, 60, 70, 80, 90 as five numbers for the sequence:

python reversed function

Important - The list_reverseiterator object is not subscriptable. Therefore, we can not access the element through indexing. If we do so, like shown in the program given below:

seq = [12, 23, 34, 45]
n = 4

print("The original sequence is:")
for i in range(n):
    print(seq[i], end=" ")

seq = reversed(seq)
print("\nThe reversed sequence is:")
for i in range(n):
    print(seq[i], end=" ")

Then it will raised the error like shown in the snapshot given below. This snapshot is taken from the output produced by above program:

python reversed function example

Therefore we need to replace the following block of code from above program:

for i in range(n):
    print(seq[i], end=" ")

with the block of code given below:

for x in seq:
    print(x, end=" ")

If you create a program like:

seq = [12, 23, 34, 45]
print(reversed(seq))

then the output you'll see, looks similar to:

<list_reverseiterator object at 0x000001E89AF18040>

which is not the output that we need. Because we need the same sequence, but in reverse. Therefore we need to wrap the reversed() inside a list. Here is the modified version of previous program:

seq = [12, 23, 34, 45]
print(list(reversed(seq)))

Now the output would be:

[45, 34, 23, 12]

Here is another example uses reversed() function to get the reversed iterator object of a sequence.

mystring = "fresherearth"
print(list(reversed(mystring)))

mylist = [1, 2, 3]
print(list(reversed(mylist)))

mytuple = (4, 5, 6)
print(list(reversed(mytuple)))

myrange = range(10)
print(list(reversed(myrange)))

The output produced by this program will exactly be:

['r', 'e', 'k', 'c', 'a', 'r, 'c', 's', 'e', 'd', 'o', 'c']
[3, 2, 1]
[6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Python Online Test


« Previous Function Next Function »