python reversed function

Python reversed() function

(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!

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:


sequenceA sequence list string, list, tuple etc.

Here are some examples:

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.

Reversing User-defined objects

To reverse user-defined objects the class must do one of the following:

  1. Implement __len__()  and __getitem()__  methods; or
  2. 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.



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!

Leave a Reply

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