“What good is an idea if it remains an idea? Try. Experiment. Iterate. Fail. Try again. Change the world.” — Simon Sinek

There are a lot of functions that python developers didn’t know. One of the most important function that most of the developers that didn’t know are Generator.

what is a generator?

A generator is a function that iterates the objects or lists or items. It will give the result one by one, rather than producing the result simultaneously. A generator is used when we use for loop to iterate an item or list.

Advantages:

  1. It eases the process of iteration in python.
  2. We can return the multiple values.
  3. It uses low spaces when we are handling a large amount of data. It is due one by one execution. This is also considered as the biggest advantage of generators.
  4. A generator is easy to implement. Because it automatically implements this __iter__(), __next__(), StopIteration function which otherwise, needs to be explicitly specified.

When and where to use a generator?

while using small data, normal function is speeder than a generator function. So prefer normal function for simple tasks. We can use a generator at all times.

Normal Functions vs Generator Functions:

A generator function is created with same keyword ‘def’ followed by function. But it returns the value through ‘yield’ keyword instead of ‘return’.

Generator function

if you look at the above example, the generator function gives the output through yield and get by the next method.

Normal function

if you look at the above example, the normal function gives the output through return method.

Using Generator function:

Unlike normal function, it returns the object instead of the list value. we can get the values from the object by following methods.

By using next keyword:

The next keyword returns the yield value one at a time. So we can yield many values and get the values through the next keyword accordingly.

The above example shows that if we use extra next keyword than yield it will give StopIteration error. It is automatically stop the iteration.

By Using List method:

In this method, we can convert generator object to list value using list keyword.This method is very simple method when compared with the other methods.

By Using for loop:

In this method, we can get the value through for loop. Using list comprehension is the best way to reduce the line of code.

These are the simple examples using a generator. In the next blog we can see the generator handling big data.

Thank you…………………..

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store