Search notes:

Python: reversed (built-in function)

In order to be able to call reversed(obj) on the object obj, obj is required to implement either

Using __len__() and __getitem__()

The following example demonstrates how reversed() is used on an object that implements __len__() and __getitem__():
class seq_one_to_four:

      def __len__(self):
          return 4

      def __getitem__(self, i):
          if i == 0: return 'one'
          if i == 1: return 'two'
          if i == 2: return 'three'
          if i == 3: return 'four'


seq = seq_one_to_four()

for e in reversed(seq):
    print(e)
Github repository about-Python, path: /builtin-functions/reversed/len-getitem.py

Using __reversed__()

This example uses __reversed__() together with the yield statement:
class class_with_reversed:

      def __reversed__(self):

          yield 'I'
          yield 'say'
          yield 'hello'
          yield 'world'


obj = class_with_reversed()

for e in reversed(obj):
    print(e)
#
#  I
#  say
#  hello
#  world
Github repository about-Python, path: /builtin-functions/reversed/reversed.py

Iterating over strings, lists etc.

Of course, because strings, lists and other sequence types implement __len__() and __getitem__(), the can be iterated over in reversed order:
for char in reversed('olleH'):
    print(char)
#
#  H
#  e
#  l
#  l
#  o

for word in reversed(['world', 'hello', 'say', 'I']):
    print(word)
#
#  I
#  say
#  hello
#  world
Github repository about-Python, path: /builtin-functions/reversed/other.py

TypeError

reversed() throws a TypeError exception if the object that is given to the function does not adhere to the required protocol (TypeError: '…' object is not reversible).

See also

Python: Built in functions

Index