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)
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