Ray Ronnaret
Ray Ronnaret

Reputation: 166

How does this prime generator code work on the first round of the loop when n=2?

I am studying generators in python. I follow the code from https://jakevdp.github.io/WhirlwindTourOfPython/12-generators.html but totally confused by the program when n=2, what exactly is the result of all(n % p > 0 for p in primes)? Per my understand, the first round of the loop, primes is empty. So how come the expression is True and adding 2 to the set?

def gen_primes(N):
    """Generate primes up to N"""
    primes = set()
    for n in range(2, N):
        if all(n % p > 0 for p in primes):
            primes.add(n)
            yield n

print(*gen_primes(100))

Upvotes: 0

Views: 62

Answers (1)

Barmar
Barmar

Reputation: 781592

From the documentation of all():

Return True if all elements of the iterable are true (or if the iterable is empty)

So when primes is empty, n % p > 0 for p in primes is empty because there's nothing to iterate over. Therefore all() returns True, and n is added to primes.

Upvotes: 3

Related Questions