kevin.k
kevin.k

Reputation: 11

Python generator only returning first instance of yield

This code should produce all prime numbers in order when 'next' is called, but it only produces 2, the first prime number of the list. The list works properly to produce prime numbers.

def genPrime():
    x = 1
    primeList = [2]
    while True:
        x += 1
        tempList = []
        for i in range(len(primeList)):
            tempList.append(x % primeList[i])
        if min(tempList) > 0:
            next = primeList[-1]
            yield next
            primeList.append(x)

prime = genPrime()
print(prime.__next__())

Upvotes: 0

Views: 182

Answers (1)

Finomnis
Finomnis

Reputation: 22818

That's exactly what a generator is supposed to do. .__next__() only returns the next item, just as the name says.

Try:

print(prime.__next__())
print(prime.__next__())
print(prime.__next__())

You will see that you get them one by one.

Further, it is important that .__next__() is not meant to be called directly. The correct way is:

print(next(prime))
print(next(prime))
print(next(prime))

If you want them all, do:

for p in prime:
    print(p)

Further, while not part of the answer, I give you a couple of programming tips:

for i in range(len(primeList)):
    tempList.append(x % primeList[i])

has an unnecessary indirection. Just do

for prime in primeList:
    tempList.append(x % prime)

Also, the entire tempList is unnecessary. Just use a for-else construct:

def genPrime():
    x = 1
    primeList = []
    while True:
        x += 1
        for prime in primeList:
            if x % prime == 0:
                break
        else:
            yield x
            primeList.append(x)

Upvotes: 1

Related Questions