[Python-Dev] Confusing listreverseiterator Behavior

Georg Brandl g.brandl at gmx.net
Tue Aug 26 22:30:56 CEST 2008


Jeff Hall schrieb:
> I realized after I fired off my response that this was still bugging
> me... it appears that the documentation is incorrect
> 
> from 2.1 Built-in Functions (v2.5 in case it matters... a quick search
> of bugs doesn't seem to show anything though)
> 
> *reversed*( 	seq)
> 
>     Return a reverse iterator. seq must be an object which supports the
>     sequence protocol (the __len__() method and the __getitem__() method
>     with integer arguments starting at |0|). New in version 2.4. 
> 
> the above appears to only be true for lists.

Not at all. (I think you misread; the __len__ method must be present on
the argument, not the returned object.)

> For tuples and strings it
> creates a reverse OBJECT which behaves slightly differently (notably by
> not including a len() method as you noticed)
> 
> I can't find how to actually create a "tuplereverseiterator" or
> "stringreverseiterator" objects... nor does there appear to be a way to
> create a "reversed" object from a list...

You don't need to. An object returned by reversed() only needs to follow
the iterator protocol. Whether it is a listreverseiterator or a general
reversed object doesn't matter.

In fact, reversed() calls __reversed__ on its argument if it exists, so that
custom types may provide their own optimized reverse iterator.

Georg



More information about the Python-Dev mailing list