Vinay Kumar

Generator Expression

Whatever programming language you are inclined towards, it's very much likely that it will support the concept of generator. Generator is a special kind of function with the following attributes.

For more clarity on generator let's compare it with a normal function. For example purpose I will be using JavaScript. We shall create both a normal function and generator function to generate even numbers within the provided limit.

From the above example we can see that a normal function will compute all the even numbers and store in an array and then return it whereas a generator will compute the value only upon execution(by calling next() method) and return it. Since generators are iterable, let's further modify the above example.

Before you start wondering real world use case scenarios for implementing generator let me point out a few of them.