Section 13: Python Generators

  Python Bootcamp 0 to Hero

< Section 12 | Section 14

Generators with Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9523120#questions

Generator functions all us to write a function that can send back a value and then later resume to pick up where it left off.

  • These allow us to generate a sequence of values over time.
  • The main difference in syntax will be the user of a yield statement.
  • When a generator function is compiled it become s an object that supports an iteration protocol.
  • This means when they are called in uyour code, the don’t actually return a value and then exit.
  • Generator functions will automatically suspend and resume their execution and state around the last point of value generation
  • The advantage is that instead of having to compute an entire series of values up front and hold it in memory, the generator computes one value then waits until the next value is called for.
    • Think of the ‘range’ function.
  • If the user actually wanted all of the values, they could use the list() function.
    • Example: list(range(0,10))

Standard ‘list’ style function example:

def cubit(n):
    result = []
    for x in range(n):
        result.append(x**3)
    return result
cubit(4)

[0, 1, 8, 27]

For this function to work, it must store the entire list in memory before sending any data back.

This example shows how to iterate through the result, but every value is already stored in memory:

for x in cubit(4):
    print(x)

0
1
8
27

yeild

Use the yield command to return values as you iterate through them without having to store all of the values in a list:

def cubit(n):
    for x in range(n):
        yield x**3
for x in cubit(4):
    print(x)

0
1
8
27

Generate Fibonacci sequence

def fibonacci(n):
    i = 0
    j = 1
    for x in range(n):
        yield j
        i, j = j, i + j
for x in fibonacci(7):
    print(x)

1
1
2
3
5
8
13

How Generators Word

The key to making generators work are the ‘Next’ function and the ‘ittr’ function:

next() function

Before we start:

def counter():
    for x in range(3):
        yield x
for num in counter():
    print(num)

0
1
2

Now try this:

def counter():
    for x in range(3):
        yield x
g = counter()
g

<generator object counter at 0x00000179756E5570>

print(next(g))

0

print(next(g))

1

print(next(g))

2

print(next(g))

————————————————————————— StopIteration Traceback (most recent call last) <ipython-input-25-1dfb29d6357e> in <module> —-> 1 print(next(g)) StopIteration:

Note! This is the same thing a for loop does, except it catches the error and stops processing!

g = counter()
while True:
    try:
        print(next(g))
    except:
        break

0
1
2

iter() function

&nbsp

s = 'hello'
for x in s:
    print(x)

h
e
l
l
o

s = 'hello'
next(s)

TypeError: ‘str’ object is not an iterator

s = 'hello'
s_iter = iter(s)
next(s_iter)

h

next(s_iter)

e

and so on…

Generator Homework Overview

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9523126#questions

 

LEAVE A COMMENT