Editor

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 lesson

Refactor 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

All Python exercises · 50 practice problems · Advanced Python quiz