-1

I'm trying to make a method that iterates over a list and returns the next element.

That's listDenominations:

[2, 5, 7, 10, 25, 30, 50, 70]

That's the method I'm working on:

class SomeClass

    def iterDenominations(self):
        it = iter(self.listDenominations)
        yield it.__next__()

# much later in the code
C = SomeClass()

When I call the method and print the result

firstCall = C.iterDenominations()
print(firstCall)
secondCall = C.iterDenominations()
print(secondCall)

, the first two prints are:

<generator object Currency.iterDenominations at 0x000001D413F6DC10>

<generator object Currency.iterDenominations at 0x000001D4140E2EB0>

These are not the results I was expecting. I'm looking for the elements to be returned sequentially from listDenominations i.e.

after firstCall: [2]

after secondCall: [5]

after thirdCall (as yet unwritten): [7], etc.

Pehaps related to this question...

Lozminda
  • 45
  • 8
goalpang
  • 1
  • 2

3 Answers3

2
iterable = iter(self.listDenominations)
for item in iterable:
    yield item

or

yield from iterable

Calling a generator function will create a generator, it will not return a value from the generator. So, you create the generator, then call next on it (or iterate over it)

denominations = c.iterDenominations()  # make the generator
first_call = next(denominations)
second_call = next(denomination)
rest = list(denominations)
print(first_call, second_call, rest)
sytech
  • 29,298
  • 3
  • 45
  • 86
1

Simple class for returning 3 next elements:

class IterDenominations(object):
    def __init__(self, numbers):
        self.iterator = iter(numbers)

    def next(self):
        print([next(self.iterator), next(self.iterator), next(self.iterator)])

Test:

ids = IterDenominations([2, 5, 7, 10, 25, 30, 50, 70])
ids.next()
ids.next()

Output:

[2, 5, 7]
[10, 25, 30]
Alderven
  • 7,569
  • 5
  • 26
  • 38
1

When you write a function with yield, calling it doesn't return that value. It returns a special type of object called a generator.To print out all the values of a generator,you will have to either loop over it with of for or pull it into a list or tuple.
Printing code:

firstCall = C.iterDenominations()
print(list(firstCall))
secondCall = C.iterDenominations()
print(list(secondCall))

Also,calling __next__ in your function is not a good practice, nor does it give you all the elements. The more pythonic way of doing so is this:

    def iterDenominations(self):
        it = iter(self.listDenominations)
        yield from it

or simply

def iterDenominations(self):
    return self.listDenominations
xkcdjerry
  • 965
  • 4
  • 15