-4

I can't get why for i in gen(100): print(i) is being used here. when i replace print(i) with print(gen(i)) it start giving memory location. I do know that yield is used for one time storage but how exactly is it working?

    def gen(num):
        i = 0
        while i<num:
            x=i
            i+=1
            if x%7 == 0:
                yield x
    for i in gen(100):
        print(i)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 2
    Possible duplicate of [What does the "yield" keyword do?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) – mx0 Sep 02 '17 at 14:06

1 Answers1

1

yield is not used for one-time storage. yield makes a function return a generator

A generator is an iterable object (which means you can use it in place of any sequences such as list(gen()), for i in gen(), etc.). You can also pass it to the next() built-in function that advances a generator one step forward (makes it begin or start where it left off and run to the first yield it hits). It also returns the yielded value

def gen():
    for i in range(5):
        yield i

print(list(gen()))  # prints [0, 1, 2, 3, 4]
print(next(gen()))  # prints 0

gn = gen()
print(next(gn))     # prints 0
print(list(gn))     # prints [1, 2, 3, 4]
print(next(gn))     # raises StopIteration, because the generator is 
                    #  exhausted (the generator function ran to completion)

The reason why you're getting a memory address from print(gen(i)) is because you're actually printing a generator object, not the value it produces. So that's why generators first have to be iterated somehow

illright
  • 3,991
  • 2
  • 29
  • 54