Keywords

What is the use of the Yield keyword in Python? What does it do?

To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.

Iterables

When you create a list, you can read its items one by one. Reading its items one by one is called iteration:

mylist = [1, 2, 3]
for i in mylist:
    print(i)
1
2
3

mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:

mylist = [x*x for x in range(3)]
for i in mylist:
    print(i)
0
1
4

Everything you can use “for... in...” on is an iterable; listsstrings, files…

These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.

Generators

Generators are iterators, a kind of iterable you can only iterate over once. Generator does not store all the values in memory, they generate the values on the fly:

mygenerator = (x*x for x in range(3))
for i in mygenerator:
    print(i)
0
1
4

It is just the same except you used () instead of []. BUT, you cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.

Yield

yield is a keyword that is used like return, except the function will return a generator.

def create_generator():
    mylist = range(3)
    for i in mylist:
        yield i*i
mygenerator = create_generator() # create a generator
print(mygenerator) # mygenerator is an object!
for i in mygenerator:
    print(i)
<generator object create_generator at 0x00000235F884DA48>
0
1
4

For more Python related blogs Visit Us Geekycodes . follow us on Instagram

Leave a Reply