Python reversed() function built-in

The python reversed() function purpose is to return an iterator of the sequence with reverse items.The function accept only one argument.The format of reversed() declaration is.

reversed( seq )

Condition on ‘seq’

The sequence ‘seq’ passed to reversed() must have the __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() with integers argument starting at 0).

The above statement means the ‘seq’ object must have a __reversed__().This function implement the reverse iteration.

Before we start using reversed() in our program you have to know that it return an iterator and this is not likely any meaningful values we expected.Consider the code below.

>>> ls=['new' , 456 , 'Six' , 'Seven']
>>> reversed( ls )
<list_reverseiterator object at 0x043CB170>

Instead of getting the reverse of ls we get ‘<list_reverseiterator object at 0x043CB170>‘.So to convert the iterator to some meaningful values use functions like list() to get the reverse of list,tuple() to get the reverse of tuple,etc.

Code example below.

>>> ls=['new' , 456 , 'Six' , 'Seven']
>>> list( reversed(ls) )
['Seven', 'Six', 456, 'new']
>>> #Getting reverse tuple
>>> tpl=(34 ,67 ,89 ,90)
>>> tuple( reversed(tpl) )
(90, 89, 67, 34)
>>> #Getting reversed dictionary
>>> dic={ 23:'Twenty-three' , 'Nm':'New Man' , 78:'Seventy-eight' , '5':'Fifth'}
>>> dict( reversed( dic) )
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    dict( reversed( dic) )
TypeError: 'dict' object is not reversible

Unfortunately we cannot reverse dictionary using reversed().

To reverse a string there is no such function as string() to obtain the reverse string from the iterator return by reversed() so we use join() instead.

>>>  s='New man!!!'
>>> ''.join( reversed(s) )
'!!!nam weN'

The concept is simple here whatever is returned by reversed() is concatenated together by join(),after the concatenation we get the reverse string.

More about join() : Python join()

Leave a Reply

Your email address will not be published. Required fields are marked *