Why Does a Python Generator Return Values Only the First Time I Loop Over It?

Asked 3 days ago 98 views

0

I’m using a generator to read records in batches, and the first loop works as expected. When I loop over the same variable again, though, nothing prints. Is that normal behavior, or am I accidentally changing the generator somewhere?

def get_ids():
    # Yield each ID instead of building a list all at once.
    yield 101
    yield 102

ids = get_ids()

# The first loop consumes the generator's values.
for item in ids:
    print(item)

# This loop has no values left to consume.
for item in ids:
    print(item)

Would converting it to a list be the right fix if I need to reuse the values, or is there a better pattern for a large dataset?

0 Answers


Write Your Answer