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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With