13 Python Generators Flashcards

1
Q

What does a generator function do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the main keyword used to create generators?

A

yield

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What type of protocol does a generator function support?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does a very simple generator function look like?

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What would a generator that calculates fibonacci numbers look like?

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the next() function do?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What happens if a generator has nothing else to yield?

A

You will get an exception.

StopIteration Traceback (most recent call last)
in ()
—-> 1 print(next(g))

StopIteration:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Are iterables and iterators the same thing?

A

No.

Strings are iterables.

But they are not iterators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What function will turn a string into an iterator?

A

iter()

s = ‘hello’
s_iter = iter(s)
next(s_iter)
‘h’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly