Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures.
Generators are of two types, generator expressions and generator functions.
As you can see we can use normal list multiple times, but generator comprehension can be used only once.
Generator expressions are useful when we are worried about memory efficiency.
However list comprehensions are much faster.
Suppose we have 10GB of text file, now lets open it and print each line.
Now the above code will definitely kills your ram and hangs your system. Since 10GB file should not be read at once, instead we can break down the file into chunks and read.
But to have less code we can use generators.
The above code just creates a generator object, it doesn't read any line until next method is called on it.
'for loop' calls the 'next' method at every iteration, so we dont have to explicitly mention it.
There we go, we have the file contents and our system is happy.
Consider the following example:
gen() is a generator function, commonly referred as a generator.
when we call gen() the statements in the function are not executed, next(result) yields value n and suspends.
Again when we call next(result) it yields n+1 value and suspends.