Modify dict/set during iteration?

metal metal29a at gmail.com
Fri Oct 30 03:02:01 CET 2009


I used this quickndirty way, any good idea to solve this problem?

def miter(iterable):
    cache = set()
    while True:
        try:
            for x in iterable:
                if x not in cache:
                    cache.add(x)
                    yield x
            break
        except RuntimeError, e:
            # Not sure if there were any other RuntimeError
            if 'changed size during iteration' in e.message:
                continue
            raise

s = set([1, 2, 3, 5, 6, 7])
for x in miter(s):
    start, stop = x, x+1
    while start-1 in s:
        start -= 1
    while stop in s:
        stop += 1
    for i in range(start, stop):
        s.discard(i)
    print '[%d:%d]' % (start, stop)

d = {'foo':1}
for x in miter(d):
    if x == 'foo':
        d['bar']=1
    print x




More information about the Python-list mailing list