Pre-PEP: reverse iteration methods
Andrew Dalke
adalke at mindspring.com
Tue Sep 23 21:47:57 EDT 2003
Raymond Hettinger:
> Proposal
> ========
>
> Add a method called iter_backwards() to sequence objects that can benefit
> from it. The above examples then simplify to::
>
> for i in xrange(n).iter_backwards():
> print seqn[i]
>
> for elem in seqn.iter_backwards():
> print elem
What about letting 'iter_backwards' be a builtin which
looks for __riter__ and if it doesn't exist, get the length
and do old-fashioned offset indexing?
Something like this untested code
def iter_backwards(obj):
try:
riter = getattr(obj, "__riter__")
except AttributeError:
n = len(obj)
while n != 0:
n = n -1
yield obj[n]
else:
for term in riter():
yield term
which would be used like
for i in iter_backwards(xrange(n)):
print seqn[i]
for elem in iter_backwards(seqn):
print elem
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list