For loops with explicit indices -- again

Armin Rigo arigo at ulb.ac.be
Tue Mar 19 12:57:29 EST 2002


Hello everybody,

Here is yet another proposal (or did I miss something similar?) about the
for-with-explicit-indices syntax problems, as discussed in PEP 281
(http://python.sourceforge.net/peps/pep-0281.html).

Now that Python has iterators, they could be more explicitely used by user
code. Remember that 'for x in sequence' is equivalent to 'for x in
iter(sequence)', where iter() is used to get a sequence iterator. 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. This just requires putting
the iterator in a local variable. 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. Maybe we should have not a 'count' but an
'index' attribute returning the current index, although it is not clear what
should then occur if we try to read 'index' before we actually enter the
loop (raise a ValueError? Or an AttributeError?).

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


Does it look reasonable or just plain counterintuitive?

Armin.





More information about the Python-list mailing list