Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures.
Generators are of two types, generator expressions and generator functions.
Generator Expressions:
Consider:
As you can see we can use normal list multiple times, but generator comprehension can be used only once.
Generator expressions are useful when we are worried about memory efficiency.
However list comprehensions are much faster.
Use Case:
Suppose we have 10GB of text file, now lets open it and print each line.
Now the above code will definitely kills your ram and hangs your system. Since 10GB file should not be read at once, instead we can break down the file into chunks and read.
But to have less code we can use generators.
The above code just creates a generator object, it doesn't read any line until next method is called on it.
'for loop' calls the 'next' method at every iteration, so we dont have to explicitly mention it.
There we go, we have the file contents and our system is happy.
Generator Functions:
Consider the following example:
gen() is a generator function, commonly referred as a generator.
when we call gen() the statements in the function are not executed, next(result) yields value n and suspends.
Again when we call next(result) it yields n+1 value and suspends.
Micropyramid is a software development and cloud consulting partner for enterprise businesses across the world. We work on python, Django, Salesforce, Angular, Reactjs, React Native, MySQL, PostgreSQL, Docker, Linux, Ansible, git, amazon web services. We are Amazon and salesforce consulting partner with 5 years of cloud architect experience. We develop e-commerce, retail, banking, machine learning, CMS, CRM web and mobile applications.
Django-CRM :Customer relationship management based on Django
Django-blog-it : django blog with complete customization and ready to use with one click installer Edit
Django-webpacker : A django compressor tool
Django-MFA : Multi Factor Authentication
Docker-box : Web Interface to manage full blown docker containers and images
More...