PEP 322: Reverse Iteration (REVISED, please comment)
pmaupin at speakeasy.net
Wed Oct 29 05:36:45 CET 2003
Raymond Hettinger wrote:
> Based on your extensive feedback, PEP 322 has been completely revised.
Personally, for some tasks I have used reverse iteration quite a bit.
My use case has _always_ been that I want to modify a list (e.g.
adding or deleting items) in situ. In all other cases which I can
recall, I have quite happily iterated in the forward direction.
(Maybe this is because I am not afraid to call list.reverse(), and
insertion/deletion is the only use case where this doesn't really help.)
This means that the implementation restrictions described in the PEP are
fine with me (because a list has the requisite methods).
However, this also means that I am most interested in how the enumerate()
interface will work with this (because the current list index must be
known in order to properly add or delete items). enumerate() was
mentioned in the PEP but not discussed in any real depth.
My personal preference (since this is the only use case which I have
ever encountered) would be to enhance enumerate in a reasonable fashion,
and not necessarily even have (or at least care about) the reverse/ireverse/
whatever name underneath enumerate().
I will happily accept whatever syntax comes along (unless the enumerate
counts 0,1,2,3... while the index of the adjacent list object is decremented
BUT, for sheer usability I think it would be wonderful if enumerate()
took an optional second argument to let it know you want to go backward.
The most general syntax for this second argument would naturally be
for idx,obj in enumerate(mylist,-1:-1:-1):
but if people think this is too ugly something simpler could be
substituted (but think about the useful possibilities of a slice
argument here before you complain too hard about the ugliness...)
Some may argue that this restricts enumerate() to certain kinds of
iterators when using the slice (and thus adds a lot of special casing),
but it may be that, realistically, if ireverse() is going to have this
special casing, and enumerate() is going to work with ireverse(), you
already have the same problem (unless the user is expected to work
with the enumerate counting backwards from the actual list index).
I cannot say this for sure, however, because I did not see (or perhaps
read closely enough) the part of the PEP which discussed enumerate.
More information about the Python-list