[Python-Dev] Confusing listreverseiterator Behavior

Armin Ronacher armin.ronacher at active-4.com
Tue Aug 26 21:05:19 CEST 2008


Hi,

I stumbled upon a confusing listreverseiterator behavior:

>>> l = [1, 2, 3, 4]
>>> i = iter(l)
>>> ri = reversed(l)
>>> len(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'listiterator' has no len()
>>> len(ri)
4
>>> ri.next()
4
>>> len(ri)
3

This is the only reverse iterator with that sort of behavior.  Is
that intentional if yes, why?  I stumbled upon that when writing a
templating engine that tried to lazily get the length of the sequence /
iterator but failed doing so after the first iteration because the
length of the reverse iterator changes every iteration.

Regards,
Armin



More information about the Python-Dev mailing list