Strange behaviour with reversed()

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 18 04:23:42 EDT 2007


On Thu, 18 Oct 2007 02:49:12 -0300, Gabriel Genellina wrote:

> A reversed object is rather simple: it stores the original sequence (a
> reference, as usual, not a copy!) and the next index to use, starting at
> len-1. Each time the next() method is called, the index is decremented
> until it goes below 0.

...

> Note that the starting index is determined at creation time, not when
> the iteration begins. So, if you create a reversed object over a list
> containing 3 elements, the first returned element will be seq[2], then
> seq[1], then seq[0]. It doesn't matter if you modify the list after
> creating the reversed object but before starting the iteration: it will
> start at seq[2] even if it's not the last item, and will silently stop
> if seq[2] is not a valid index anymore.

You know, that's probably the *least* intuitive behaviour possible.

For reversed() to iterate over the input as it was at creation time is a 
reasonable design choice; for it to iterate over the input as it is at 
call time is also a reasonable design choice; but for it to iterate over 
some unholy mutant melding of the sequence as-it-was and as-it-is is 
simply bizarre. I hope it just fell out of the implementation and wasn't 
a deliberate design choice.


-- 
Steven.



More information about the Python-list mailing list