[Python-Dev] Yet another (?) for-with-indices

Armin Rigo arigo@ulb.ac.be
Sat, 9 Mar 2002 19:18:00 +0100


Hello everybody,

Here is yet another proposal (or did I miss something similar?) about the
for-with-explicit-indices syntax problems. Now that Python has iterators,
they could be more explicitely used by user code. More specifically, as it
seems we often loop over sequence elements and occasionnally need an
explicit index, I suggest adding a 'count' attribute to sequence iterators
that returns the number of items returned so far, that is, the index of the
*next* item (as stored in the iterator in C):

    it = iter(lst)
    for x in it:
        if need_the_index_of_x:
            index = it.count-1

For example, to decrement all positive integers in a list, modifying it
in-place:

    it = iter(lst)
    for x in it:
        if x>0:
            lst[it.count-1] -= 1

No syntax sugar is required. All the trick is in explicitely naming the
iterator object used by the loop. This idea could maybe be extended to make
the attribute writeable. For example, inside a loop:

    it.count += 1    # skip next element
    it.count -= 1    # process the same element again
    it.count = 0    # full rewind
    it.count -= 1; del lst[it.count]    # remove bad item from list


Thanks,

Armin.