Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function returns generator instead of list

I wanted to play around with primes in Python and therefore use a function to create a Sieve of Eratosthenes:

def primes(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for (i, isprime) in enumerate(a):
        if isprime:
            yield i
            for n in range(i*i, limit, i):
                a[n] = False
    return list(a)

In my opinion this function should definitely return a list but when I do print(primes(1000)) I only get <generator object primes at 0x0000000002C5C558> as the output. When using print(list(primes(1000))) everything works as expected (the list of primes is printed).

What am I missing?

Why does the function return a generator instead of a list?

like image 612
snrlx Avatar asked May 08 '26 16:05

snrlx


1 Answers

Because you used a yield expression in the function.

In the sieve, a is a mask, not the final list of primes produced. You don't want to return that list, really.

If you wanted the function to return a list and not act as a generator, collect the primes in the function:

def primes(limit):
    a = [True] * limit
    a[0] = a[1] = False
    primes = []

    for (i, isprime) in enumerate(a):
        if isprime:
            primes.append(i)
            for n in range(i*i, limit, i):
                a[n] = False

    return primes
like image 104
Martijn Pieters Avatar answered May 11 '26 06:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!