[Python-Dev] a feature i'd like to see in python #1: better iteration control

"Martin v. Löwis" martin at v.loewis.de
Sun Dec 3 15:16:45 CET 2006


Ben Wing schrieb:
> i'd much rather see something like:
> 
> for x:iter in list:
>   ...do something...
>   if x should be deleted:
>     iter.delete()

You can easily implement that feature yourself if you need it,
at least for lists (or sequences that support integer indexing):

class deletable_iter:
    def __init__(self, sequence):
        self.sequence = sequence
        self.last = -1

    def __iter__(self):
        return self

    def next(self):
        self.last += 1
        try:
            return self.sequence[self.last]
        except IndexError:
            raise StopIteration

    def delete_last(self):
        del self.sequence[self.last]
        self.last -= 1

You use this class like this:

x = [1,2,3,4,5,6,7,8]
y = deletable_iter(x)
for i in y:
    print i
    if i%2 == 0:
        y.delete_last()

print x

This cannot be generalized for the iteration protocol,
because it might not be possible for the iterator to
delete an element after it has returned it.

Notice that this version "supports" multiple invocations
of delete_last in a single step; it may be useful to
allow at most one deletion, and raise an exception if
a second deletion is attempted.

Even if the deletion was added to the iterator protocol
(which would require a PEP, IMO), I don't think the
syntax should be changed. If you want access to the
iterator in the loop, you should explicitly assign it
to a variable before entering the loop.

Regards,
Martin



More information about the Python-Dev mailing list