Why is my code faster with append() in a loop than with a large list?

Piet van Oostrum piet at cs.uu.nl
Mon Jul 6 17:51:02 CEST 2009


Sorry, there was an error in the sieve in my last example. Here is a
corrected version:

D = {9: 6} # contains composite numbers
Dlist = [2, 3] # list of already generated primes
def sieve():
    '''generator that yields all prime numbers'''
    global D
    global Dlist
    for q in Dlist:
        yield q
    while True:
        q += 2
        p = D.pop(q, 0)
        if p:
            x = q + p
            while x in D: x += p
            D[x] = p
        else:
            Dlist.append(q)
            D[q*q] = 2*q
            yield q

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list