The goal of this blog post is to provide a quick explanation of what a generator is and a short code
snippet demonstrating it.
Generators are functions
that can be used as iterators. Another way of saying the same thing is that a generator is a function which may return as many times as needed, instead of just once.
A good way to
demonstrate a generator is via the Fibonacci Sequence.
def fib():
a,b = 0, 1
while True:
yield a
a, b = b, a+b
for f in fib():
if f > 100:
break
print(f)
The pro of generators is that they require less memory because you only generate the values as you need them. The con is that you are increasing the workload on your CPU and making your code more complex.
If you are interested in learning the details, please refer to the items:
If you are interested in learning the details, please refer to the items:
3.
Python Documentation
a.
Glossary
v.
Generator
vii.
Generator Iterator
viii.
Iterable
ix.
Iterator
x.
Sequence
b.
PEPs
c.
Python Language
Reference
i.
Compound Statements
ii.
Data Model
A.
Special Method Names
I.
Emulating Containter
Types
iii.
Expressions
A.
Atoms
e.
Examples
iv.
Simple Statements
d.
Python Standard Library
i.
Built-In Exceptions
A.
Concrete Exceptions
ii.
Built-In Functions
A.
next(...)
iii.
Built-In Types
II.
Generator Types
III.
iterator.__iter__()