What Are Generators In Python?

In this tutorial, we will learn about Python generators and their benefits in detail with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.
Definition
- Functions that return an iterable set of items ( produces a sequence of items - one at a time.)
- It look like typical functions but their behavior is different.
- It uses the yield statement ( one or more yield statements) instead of the return. ( to return a generator object.)
- calling the generator function doesn’t run the function: it only creates a generator object.
- The generator code executes when
- the next function is applied to the generator object or
- if the generator is iterated over (in this case, the next function is implicitly called)
Application
- Memory Efficient: In normal function, all sequence is generated at once and stored in a memory but using a generator returns a sequence as needed by yield
- Generate Infinite Stream
- Easy to Implement
Example 1
squares_generator = (i * i for i in range(5))
print(squares_generator)
Output
# returns a generator object:
<generator object <genexpr> at 0xx..
Example 2
squares_generator = (i * i for i in range(5))
print(squares_generator.__next__())
print(squares_generator.__next__())
print(squares_generator.__next__())
Output
0
1
4
Example 3
# iterate over the generator and print the values
for i in squares_generator:
print(i)
To know about it, please refer to the official documentation website - official website.
Next Tutorial
- What Is Python, Its Benefits And Features?
- What Is Pickling And Unpickling In Python?
- Memory Management In Python
- What Is The __Init__ In Python?
- Difference Between List And Tuple
- What Is The Self Keyword In Python?
- What Is The Lambda Function In Python?
- What Is A Break, Continue, And Pass Statement In Python?
- What Are The Common Built-In Data Types In Python?
- What Is The Difference Between .Py And .Pyc Files In Python?
- What Are Decorators In Python?
- What Is Slicing In Python?
- What Are Negative Indexes In Python?
- What Is List And Dictionary Comprehension In Python?
- What Is A Docstring In Python?
- What Are Python Iterators?
- What Are *Args And **Kwargs In Python And How To Use Them?
- What Is The Pythonpath Variable In Python?
- What Are Namespaces In Python?
- What Is Pep8 (Python Enhancement Proposals) In Python?
- What Is The Split(), Join(), Sub(), And Subn() Method In Python?
- What Are Modules And Packages In Python?
- What Is Scope Resolution In Python?
- Is Python Compiled Or Interpreted Language?
- What Are Generators In Python?