

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 10
click for more info
Not enough gems
Cost: 6 gems
1: Linked Lists
incomplete
2: Linked List vs. List
incomplete
3: Generators
incomplete
4: Iterating
incomplete
5: Add to Tail
incomplete
6: Add to Head
incomplete
7: Linked List Queue
incomplete
8: Remove from Head
incomplete
9: Linked List Queue Quiz
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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.
yield KeywordThe 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.
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.
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.