+ 18
For generators, why write 'yield'? Why not write 'return' or 'print'? Could someone explain the concept of generators?
3 Answers
+ 22
The generator in python allows you to declare a function that is used like an iterator. It is used so that you don't have to create additional variables where you have to iterate it.
for example:
this is using the conventional way:
def func(n):
num = 0
nums = []
while num < n:
nums.append(num)
num += 1
return nums
example=sum(func(10000))
print(example)
the same using a generator:
def func(n):
num = 0
while num < n:
yield num
num += 1
example=sum(func(10000))
print(example)
Note: the first example builds and returns a list, but the second example yields items instead of returning a list.
Both give the final answer of 49995000, but the first example stores all the items in a list that takes a lot of memory while the second example saves a ton.
Hope this helps.
+ 3
# you will get a reasonable starting introduction here.
# https://jeffknupp.com/blog/2013/04/07/improve-your-JUMP_LINK__&&__python__&&__JUMP_LINK-yield-and-generators-explained/
# A simple generator example is
def a_yielding_function():
num = 0
while 1:
yield num
num += 4
the_generator = a_yielding_function()
# type will quickly show you wether you are looking at
# a function or a generator class object as you try to
# construct them yourself or look at peoples examples.
print(type(the_generator))
for i in range(6):
print(next(the_generator))
+ 1
The yeild kyword simply return a result to caller without destroying local variables. In case of return it terminate the function and destroy local variables