Tuesday, April 30, 2013

Generator and yield explained simply

I know though some of you are already using Python for some time, you still get confused when you hear the term generator and yield. Let me show you a simple program that explains it easily:
my_li = ['a', 'b', 'c', 'd']

def generator_example(my_li):
    for item in my_li:
        yield item, 1

x = generator_example(my_li)
print type(x)
print x
for item in x:
    print item
Now, if you run the program, you will see the following output:


('a', 1)
('b', 1)
('c', 1)
('d', 1)
So, you see, the function generator_example returned a generator! We are used to see return in functions that returns a value (variable, list, dictionary etc.). But what if you want to return a series (sequence) of items instead of a single value? There you need to use yield. So in the loop (for item in my_li:) for every item in the list you return (actually yield) a tuple (the item and 1) and calling yield you don't get out of the function generator_example, rather you continue yielding for all the items in the list and then get out of the function. Now the return value of the function is stored in x. If you print the type of x, you will see it is and if you print the value of x, you see that it's a generator object. What do you do with this? You can iterate over x using loop and get the actual values. But you can iterate only once. Now you need another program to get it more clear? This example is even simpler:
my_li = ['a', 'b', 'c', 'd']

def generator_example(my_li):
    for item in my_li:
        yield item.upper()

x = generator_example(my_li)
print type(x)
print x
for item in x:
    print item
This page also has some good explanations: http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained

No comments: