Programming & syntax · reviewed in August 2026
Generator
A generator is a Python function that uses yield instead of return to produce a sequence of values one at a time, on demand, instead of building the whole list in memory upfront. Each call to next() resumes the function exactly where it left off.
def even_numbers(up_to):
n = 0
while n < up_to:
yield n
n += 2
for even in even_numbers(10):
print(even)Frequently asked questions
How is it different from a normal function?
A normal function computes and returns its whole result at once; a generator pauses execution at each yield and only resumes when something asks for the next value, without recomputing what came before.
Why use a generator instead of a list?
Because it doesn't reserve memory for the whole sequence upfront — useful for walking huge files or data streams where loading everything into a list would be too costly.
Can a generator be iterated more than once?
Not directly: once exhausted, a generator doesn't reset itself. If you need to walk it again, you have to call the function that creates it again.