Creating generators objects in python

Sunday, June 2, 2013

What is Generator?

A generator is a function which can stop whatever it is doing at an arbitrary point in its body, return a value back to the caller, and, later on, resume from the point it had `frozen' and merrily proceed as if nothing had happened (link) . Here is a simple example: 

if you write 

x = [n for n in foo if bar(n)]

you can get the list object assigned to the x.

x=(n for n in foo if bar(n))
you can get out the generator and assign it to x. Now it means you can do

Now we understand the difference

>>> my_list = [1, 3, 5, 9, 2, 6]
>>> filtered_list = [item for item in my_list if item > 3]>>> print filtered_list
[5, 9, 6]
>>> len(filtered_list)

>>> filtered_gen = (item for item in my_list if item > 3)
>>> print filtered_gen
<generator object at 0xb7d5e02c>
if you try to get the length of filtered_gen it will throw a error about 
object of type 'generator' has no len()