yield
is a keyword in Python
that is used like return
. With
yield
keyword
function returns a generator
object.
Benefit of having generator object is that it does not store all the values in memory, it generates the values
on the fly.
Let's understand use of yield
with below example.
yield
example
items = [{"code" : 541336, "name" : "NNTC"},
{"code" : 513377, "name" : "MMTC"},
{"code" : 513677, "name" : "PTC"},
{"code": 312677, "name": "ZTC"},
{"code" : 612677, "name" : "ITC"},
{"code" : 562677, "name" : "KTH"},
{"code" : 514677, "name" : "RTC"}
]
yield
def func_gen(items):
for count, item in enumerate(items):
if count % 2 == 0:
yield (item)
gen_object = func_gen(items)
print(type(gen_object))
for item in gen_object:
print(item)
<class 'generator'>
{'code': 541336, 'name': 'NNTC'}
{'code': 513677, 'name': 'PTC'}
{'code': 612677, 'name': 'ITC'}
{'code': 514677, 'name': 'RTC'}
yield
in Python
items = [{"code" : 541336, "name" : "NNTC"},
{"code" : 513377, "name" : "MMTC"},
{"code" : 513677, "name" : "PTC"},
{"code": 312677, "name": "ZTC"},
{"code" : 612677, "name" : "ITC"},
{"code" : 562677, "name" : "KTH"},
{"code" : 514677, "name" : "RTC"}
]
def func_gen(items):
for count, item in enumerate(items):
if count % 2 == 0:
yield (item)
gen_object = func_gen(items)
print(type(gen_object))
for item in gen_object:
print(item)
Similar Articles