Refactor to a Generator
Intermediate · Refactor · from Python Generators: Process Millions of Items Without Running Out of Memory
From the lesson: How Much Memory Do Generators Actually Save?
The memory difference is dramatic. A list of 10 million integers takes roughly 80 MB of RAM. A generator that yields the same values uses a constant ~120 bytes regardless of how many items it produces.
Read this part of the lessonRefactor this function to use yield instead of building and returning a list. The output should remain the same.
def get_powers_of_two(n):
result = []
power = 1
for _ in range(n):
result.append(power)
power *= 2
return result
for p in get_powers_of_two(6):
print(p)def get_powers_of_two(n):
result = []
power = 1
for _ in range(n):
result.append(power)
power *= 2
return result
for p in get_powers_of_two(6):
print(p)
More Generator exercises
- Your First GeneratorIntermediate
- Predict the Generator OutputIntermediate
- Flatten with yield fromAdvanced
- Build a Data PipelineAdvanced
- Fix the Generator BugAdvanced
- Infinite Fibonacci GeneratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz