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]
Ca
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+1
else:
return self.__next__()
else:
raise StopIteration