Saturday, March 15, 2014

Generator function in Python or How to use yield

What are generator functions

A Generator function  in Python is essentially a custom iterator to be used a loop. For example, it can be used to create a custom iterator that will walk through a date range e.g. return all dates between an start and end date or you could  Iterate over all prime numbers.

How to declare a generator function

A generator function is declared like any other function in python but instead of using return you will have to use the yield statement.

Iterate through prime numbers

As calculating prime numbers can be quote intense I will concentrate on the first 100. 
Here comes the code:

In the example we declared two functions, def is_prime(num) and def prime_iter(low,high).
The first function is_prime(num) is checking if a number is actually a prime number or not.

The function prime_iter(low,high) is the interesting function for us now as it acts similar to the python range command (though range is NOT an generator). We provide a start and end value and our function will return a valid prime number (if any). As you can see, by using yield python returns a value for further processing to the requesting loop and will continue with the next iteration. The iteration ends if no value is returned.

Let me know if this post was helpful or if you need further examples. Or did I make a mistake ? Please do let me know!

Source code available at :

No comments:

Post a Comment