Python | yield in python

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.

Python yield example

1. Define a Python List
   
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"}
        ]
     
2. Create generator function with yield
   
def func_gen(items):
    for count, item in enumerate(items):
        if count % 2 == 0:
            yield (item)
 
3. Iterate the generator object
   
gen_object = func_gen(items)
print(type(gen_object))

for item in gen_object:
    print(item)
 
Output
   
<class 'generator'>
{'code': 541336, 'name': 'NNTC'}
{'code': 513677, 'name': 'PTC'}
{'code': 612677, 'name': 'ITC'}
{'code': 514677, 'name': 'RTC'}
 
Example code snippet for using 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)
 

Follow US on Twitter: