13 Python Generators Flashcards
What does a generator function do?
Generator functions allow us to write a function that can send back a value and then later resume to pick up where it left off. This type of function is a generator in Python, allowing us to generate a sequence of values over time. The main difference in syntax will be the use of a yield statement.
What is the main keyword used to create generators?
yield
What type of protocol does a generator function support?
iteration protocol
The main difference is when a generator function is compiled they become an object that supports an iteration protocol. That means when they are called in your code they don’t actually return a value and then exit. Instead, generator functions will automatically suspend and resume their execution and state around the last point of value generation.
What does a very simple generator function look like?
def gencubes(n): for num in range(n): yield num**3
for x in gencubes(10):
print(x)
0 1 8 27 64 125 216 343 512 729
What would a generator that calculates fibonacci numbers look like?
def genfibon(n): """ Generate a fibonnaci sequence up to n """ a = 1 b = 1 for i in range(n): yield a a,b = b,a+b
for num in genfibon(10):
print(num)
1 1 2 3 5 8 13 21 34 55
What does the next() function do?
The next() function allows us to access the next element in a sequence. Lets check it out:
def simple_gen(): for x in range(3): yield x
# Assign simple_gen g = simple_gen()
print(next(g))
0
What happens if a generator has nothing else to yield?
You will get an exception.
StopIteration Traceback (most recent call last)
in ()
—-> 1 print(next(g))
StopIteration:
Are iterables and iterators the same thing?
No.
Strings are iterables.
But they are not iterators.
What function will turn a string into an iterator?
iter()
s = ‘hello’
s_iter = iter(s)
next(s_iter)
‘h’