Skip to content Skip to sidebar Skip to footer

Python Iterator Returning Unwanted 'none'

Why is my iterator returning extra 'None' in the output. For the parameters/example below, I am getting [None,4,None] instead of the desired [4] Can anyone explain why I am getti

Solution 1:

As people in the comments have pointed out, your line if (self.purchase[old])%(self.d) == 0: leads to the function returning without any return value. If there is no return value supplied None is implied. You need some way of continuing through your list to the next available value that passes this test before returning or raising StopIteration. One easy way of doing this is simply to add an extra else clause to call self.__next__() again if the test fails.

def__next__(self):
        if self.i < self.length:
            old = self.i
            self.i += self.n
            if (self.purchase[old])%(self.d) == 0:
                print("returning")
                return old+1else:
                return self.__next__()
        else:
            raise StopIteration

Solution 2:

Functions return None if you don't have an explicit return statement. That's what happens in __next__ when if (self.purchase[old])%(self.d) == 0: isn't true. You want to stay in your __next__ until it has a value to return.

classPrizes(object):
    def__init__(self,purchase,n,d):
        self.purchase = purchase
        self.length = len(purchase)
        self.i = n-1
        self.n = n
        self.d = d

    def__iter__(self):
        return self

    def__next__(self):
        while self.i < self.length:
            old = self.i
            self.i += self.n
            if (self.purchase[old])%(self.d) == 0:
                return old+1raise StopIteration

defsuperPrize(purchases, n, d):
    returnlist(Prizes(purchases, n, d))

purchases = [12, 43, 13, 465, 1, 13]
n = 2
d = 3print(superPrize(purchases, n, d))

Post a Comment for "Python Iterator Returning Unwanted 'none'"