What is a Generator?

A generator is a function which returns an iterator (A basic Python object that can be iterated over). When a normal Python function is called, the execution starts at the first line of the function and continues until it encounters a return statement or an exception or the end of the function (implicit return None). Once the execution returns to outside the function, all local instances of the function are lost. A generator is a function that is able to ‘yield’ its returnable values until required. Thus, it is able to generate its returnable values on demand, thereby saving a lot of memory for large lists. They are a very useful way of iterating over sequences that at are essentially infinite in length.

* Generators are iterables that can be only iterated once.

Basic Example

Let’s go through a basic example of how generators work –

def my_generator():
 for i in range(5):
yield i*i

 

>>>print(my_generator())
<generator object my_generator at 0xb5487b24>
>>>gen=my_generator()
>>>gen.next()
0
>>>gen.next()
1
>>>gen.next()
4
>>>gen.next()
9
>>>gen.next()

What is the use of Generators?

However redundant this might see, generators are pretty useful when the results of the steps of iteration are required in different places and when a large set of values needs to be returned.

When the code execution starts at the first line of the function, it only continues till it encounters a yield statement. This value is returned when the next() method is called on the generator object, and then the execution starts again till the next yield is encountered.

To sum up the aforesaid –

  • Generators give the ability of lazy evaluation.
  • Generators help us break down the result of a lengthy iteration as required.
  • Generators allow us to capture results without redundant/unnecessary memory allocation.
  • They allow execution speeds faster than even list comprehension.
  • Infinite loop execution is not a problem with generators.

That’s it for this article, if you want to read such articles, you can read it here. If you have any queries, you can ask in the comment section.

Share This