Strange behaviour with reversed()

Andreas Kraemer akraemer at sbcglobal.net
Fri Oct 19 18:30:21 EDT 2007


On Oct 19, 1:49 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Andreas Kraemer <akrae... at sbcglobal.net> wrote:
> >> The only other behaviours I would regard as intuitive for iteration over
> >> a mutating sequence would be to throw an exception either for mutating
> >> the sequence while the iterator exists or for using the iterator after a
> >> mutation.
>
> > Maybe it would have been slightly more intuitive if reversed() had
> > been implemented like this,
>
> > def Reversed(seq):
> >   for i in xrange(len(seq)-1,-1,-1):
> >     yield seq[i]
>
> > so that the length of the sequence is determined when the iteration
> > starts, not when the iterator is created?
>
> Perhaps, but either way it comes down to "don't modify the sequence while
> iterating".

Definitely agreed.




More information about the Python-list mailing list