The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Recent Posts

Python - Generators and use of yield statement explained

Introduction:
The yield statement is used when defining a generator function (used in the body of the generator function). Using a yield statement in a function definition results in creating a generator function instead of a normal function. Unlike return keyword, yield helps the caller to provide the results without destroying the local variables and hence it will resume from where it left off, oppose to using new set of variables for each call like normal function.

Enough of 'yield' intro, let's dive into generator concept.

Generators

Generators:
In simpler words generators behave same like a list whereas the only difference is it will calculate a series of results on demand, i.e each element is calculated lazily.

a_list = [i for i in range(7)]

a_generator = (i for i in range(7))

Okay, so do we get length for a generator ? Try it on your own and comment the result with explanation.

Hint: Even though the generators are iterable like a list but they are not a collections (list, set, tuples etc) and hence __ length :)

Hence a generator calculates a value on demand so it doesn't have any idea about its own result set

Use case ?
Yes you guessed it, generators are used for memory intensive tasks, where the complete results are not needed, just yielding the intermediate results to the caller until the requirement is satisfied and further processing stops

Example:
Best example is searching. Yes when you are looking out for something say in a file for a particular keyword, you would be more happy when you get the first searched result instead of the search engine to go through the full file and return you the result. Sounds good right :)

Please click on the below git hub link for example explained using python code,
https://github.com/ravic499/blog-tips-python/blob/development/advanced_python/generators_and_yield.py

References:
https://www.pythoncentral.io/python-generators-and-yield-keyword/

No comments