generators
Introduction
In this article you will learn what generators in Python 3 are.
Create a file
generators_demo.py
and copy the code from the examples into it.
You can run the file with the command
python3 generators_demo.py
You can move through the objects of a list in different ways. If the list
is small, what works well is, for example, the function
enumerate
Generators are needed for large objects. For example, for ones that do not fit
in memory.
Since it is impossible to load them whole, ordinary ways of iterating do not work and
generators come to the rescue.
The idea is that only the next
element of the object is passed in a special way - this is called lazy evaluation or lazy evaluation
The keyword by which you can recognize a generator in code
is yield
A generator can also include ordinary return but to be
a generator it needs at least one yield
def gen123():
yield 1
yield 2
yield 3
g = gen123()
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g)) # comment it out for the rest of the code to work
python generators_demo.py
<generator object gen123 at 0x01AADCD8>
1
2
3
Traceback (most recent call last):
File "generators_demo.py", line 12, in
Each call of a generator function creates a new generator object
h = gen123()
i = gen123()
print(h)
print(i)
print(h is i)
<generator object gen123 at 0x00F7DD48>
<generator object gen123 at 0x00F7DD80>
False
Accordingly, iteration over them is independent too
print(next(h))
print(next(h))
print(next(i))
1
2
1
def gen246():
print("About to yield 2")
yield 2
print("About to yield 4")
yield 4
print("About to yield 6")
yield 6
print("About to return")
g = gen246()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
python generators_demo.py
About to yield 2
2
About to yield 4
4
About to yield 6
6
About to return
Traceback (most recent call last):
File "generators_demo.py", line 43, in
We will look at more complex cases of using generators in the following articles:
Article author: Andrei Olegovich