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
solved why for loop is used to generate numbers through function?