Python reversed() method
The reversed()
method returns the reversed iterator of the given sequence. It is the same as the iter() method but in reverse order. Internally, it calls the __reversed__()
method of the sequence class. If the given object is not a sequence, then override __reversed__()
method in the class to be used with the reversed()
function.
Syntax:
reversed(seq)
Parameters:
seq: The sequence to be reversed.
Return Value:
Returns an iterator object that accesses the given sequence.
The following example returns the reversed iterator of the specified string sequence.
mystr = "Hello"
rev_itr = reversed(mystr)
print(type(rev_itr))
print(rev_itr.__next__()) # getting item using __next__()
print(next(rev_itr)) # getting item using next() which calls __next__()
print(next(rev_itr))
print(next(rev_itr))
print(next(rev_itr))
#print(next(rev_itr)) # raise StopIteration error
<class 'reversed'>
o
l
l
e
H
Above, reversed(mystr)
returns an object of the reversed
iterator class.
Since, this is an iterator, you can use the __next__()
or next() method to access values.
Calling the next()
method after getting the last element will raise the StopIteration
error.
The reversed()
function can be used with the for loop, as shown below.
mystr = "Hello"
for s in reversed(mystr):
print(s, end='')
olleH
The sequence can be a list, tuple, set, or dict. The following get reversed iterators of different iterables.
nums_list = [1,2,3,4]
rev_itr = reversed(nums_list)
print(next(rev_itr))
print(next(rev_itr))
print(next(rev_itr))
print(next(rev_itr))
nums_tuple = (10, 20, 30, 40)
rev_itr = reversed(nums_tuple)
print(next(rev_itr))
print(next(rev_itr))
print(next(rev_itr))
print(next(rev_itr))
4
3
2
1
40
30
20
10
The reversed()
method returns an object, which can be converted into a list, tuple, or set to view the elements of the returned object, as shown below.
mystr = "Hello"
print(list(reversed(mystr)))
nums_list = [1,2,3,4]
print(tuple(reversed(nums_list)))
nums_tuple = (10, 20, 30, 40)
print(set(reversed(nums_tuple)))
['o', 'l', 'l', 'e', 'H']
(4, 3, 2, 1)
{40, 30, 20, 10}