(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python reversed() function
Updated on Jan 07, 2020
The reversed()
function allows us to process the items in a sequence in reverse order. It accepts a sequence and returns an iterator.
Its syntax is as follows:
Syntax:
reversed(sequence) -> reverse iterator
Parameter | Description |
---|---|
sequence |
A sequence list string, list, tuple etc. |
Here are some examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>>
>>> reversed([44, 11, -90, 55, 3])
<list_reverseiterator object at 0x7f2aff2f91d0>
>>>
>>>
>>> list(reversed([44, 11, -90, 55, 3])) # reversing a list
[3, 55, -90, 11, 44]
>>>
>>>
>>> list(reversed((6, 1, 3, 9))) # reversing a tuple
[9, 3, 1, 6]
>>>
>>> list(reversed("hello")) # reversing a string
['o', 'l', 'l', 'e', 'h']
>>>
|
Try it out:
To produce the result at once we have wrapped reversed()
in a list()
call. This is required in both Python 2 and Python 3.
The argument passed to reversed()
must be a proper sequence. Trying to pass objects which do no maintain their orders like dict
and set will result in a TypeError
.
1 2 3 4 5 6 7 8 9 10 11 12 | >>>
>>> reversed({0, 4, -2, 12, 6})
Traceback (most recent call last):
File "", line 1, in
TypeError: argument to reversed() must be a sequence
>>>
>>>
>>> reversed({'name': 'John', 'age': 20})
Traceback (most recent call last):
File "", line 1, in
TypeError: argument to reversed() must be a sequence
>>>
|
Reversing User-defined objects #
To reverse user-defined objects the class must do one of the following:
- Implement
__len__()
and__getitem__()
methods; or - Implement
__reversed__()
method
In following listing, the CardDeck
class implement __len__()
and __getitem__()
methods. As a result, we can apply the reversed()
on the CardDeck
instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | >>>
>>> from collections import namedtuple
>>>
>>> Card = namedtuple('Card', ['rank', 'suit'])
>>>
>>> class CardDeck:
... suits = ('club', 'diamond', 'heart', 'spades')
... ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA")
...
... def __init__(self):
... self._cards = [Card(r, s) for s in self.suits for r in self.ranks ]
...
... def __len__(self):
... return len(self._cards)
...
... def __getitem__(self, index):
... return self._cards[index]
...
... # def __reversed__(self): this is how you would define __reversed__() method
... # return self._cards[::-1]
...
...
>>>
>>> deck = CardDeck()
>>>
>>> deck
<__main__.CardDeck object at 0x7f2aff2feb00>
>>>
>>>
>>> deck[0], deck[-1] # deck before reversing
(Card(rank='2', suit='club'), Card(rank='A', suit='spades'))
>>>
>>>
>>> reversed_deck = list(reversed(deck))
>>>
>>>
>>> reversed_deck[0], reversed_deck[-1] # deck after reversing
(Card(rank='A', suit='spades'), Card(rank='2', suit='club'))
>>>
|
Try it out:
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments