Python Generators and Yield

In the previous blog, we have seen how we can build an iterator using __iter__() and __next__() method. In this blog, we will learn an easy and fast way to make our own iterator.

Generators return an iterator object in a simple fashion. Let’s see how we can make generators in Python:

Generator Function: This is the same as the normal function. The only difference is that we use yield statement instead of return. The return statement terminates the function while the yield statement pauses the function and starts from that point again whenever called. Let’s see by an example

The output looks like this

The Odd() function used above is of type generator and ‘a’ is a generator object.

Calling yield, saves all states(x in above code) and continues from that point on calling again next(a) returns 3). To iterate again we have to create a new generator object.

We can also use generators with for loop directly.

So, whenever we use yield instead of return, we end up making a generator function.

Generator Expression: This is similar to the list comprehension. Only replace the square bracket with the round. Let’s see an example

Pros: The generator expression gives one element at a time(Lazy evaluation), unlike list comprehensions that output the entire list. Thus, generator expressions are more memory efficient than list comprehensions.

To find the next element in generator expression, use the next() function. Let’s take above code

So, you have learned 3 methods to build an iterator namely:

  1. using __iter__() and__next__() methods(See Python Iterators)
  2. Generator functions
  3. Generator expressions

Using Generators to create an iterator is a fast, easy way but if you want to add extra methods to the iterator object, better switch to the first method.

Now, you might have got some feeling about the Python Generators and yield. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

 

Leave a Reply