Posts

Showing posts from April, 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 ge