How to use Generators in Python?

In Python, creating a iterator is a bit tricky, we need to implement _iter_( ) and _next_( ) method to keep track of internal states and raise StopIteration when there is no value to be returned. So in such cases, Generators are used.

What is Python Generators?

Python generator is a special type of function that returns a traversal object which is used to create iterators. In a generator function yield keyword is used rather than return.

Difference between yield and return statement

If a function contains at least one yield statement it becomes a generator function. Both yield and return will return some value from a function. But return statement terminates the function entirely whereas yield statement pauses the function temporarily holding all the internal states of the function and continues in further successive calls.

Difference between Generator function and normal function:

  • Generator function has one or more yield keywords.
  • When called, it returns a traversal object (iterator) but does not start immediately
  • Once the function yields, the function is paused and control is transferred to the caller.
  • Local variables and their states are remembered between successive calls
  • Methods like _iter_() and _next_() are implemented automatically. We can iterate using next().
  • When function terminates, StopIteration is raised automatically.
Example:

As you can see in the above example, when the function terminates, StopIteration is raised automatically.

Python Generator with a Loop:

Normally generator functions are implemented in a loop with a terminating condition.

Generator Expression:

            Simple Generators can be created on the go using Generator expressions. It’s similar to lambda expression, which creates anonymous function. Generator expression also creates anonymous function.

            Syntax is like list comprehension in Python. But instead of a square bracket round parentheses is used. The list comprehension calculates entire list whereas generator expression calculates one at a time.

Advantages:

  • Easy to implement
  • Memory efficient
  • Represent infinite sequence
  • Pipelining with generators.