We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Generators

Our LinkedList is missing an easy way to loop over its nodes, but before we can build that, you should know about generators.

A generator is an object that produces a sequence of values one at a time, as they're needed.

The yield Keyword

The yield keyword in Python returns a value, kind of like return. However, it's used to turn the function into a generator function.

Calling a generator function creates a new generator object. When that generator is run, it executes the code in the generator function until it hits a yield statement. Then the generator pauses and returns the yielded value. The next time the generator runs, it picks up where it left off.

def create_message_generator():
    yield "hi"
    yield "there"
    yield "friend"


gen = create_message_generator()
print(next(gen))  # hi
print(next(gen))  # there
print(next(gen))  # friend

Each call to create_message_generator() creates a new generator instance, and each generator keeps track of where it paused. To keep using the same generator and have it resume, assign it to a variable like gen. Then you can call next() on it repeatedly or loop over it.

Yielding in a Loop

Hardcoding one yield per value gets old fast. Generators really shine when you yield inside a loop:

def create_counter():
    count = 0
    while True:
        yield count
        count += 1


for count in create_counter():
    print(count)
    if count == 2:
        break
# 0
# 1
# 2

The while True may look scary, but it's safe here: the generator pauses at yield in every loop iteration, and it only advances when the caller asks for the next value.

Notice that a standard for loop automatically handles calling next() under the hood.

Assignment

Another one of the CEO's posts went viral, and LockedIn's servers can't keep up. The team needs you to implement exponential backoff so that requests wait longer and longer between retries.

Complete the backoff_delays function. It's a generator function that yields retry delays in seconds.