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.
- It eases the process of iteration in python.
- We can return the multiple values.
- 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.
- 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’.
if you look at the above example, the generator function gives the output through yield and get by the next method.
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.