A generator is a special kind of function that produces a sequence of values lazily, one at a time, using yield instead of return. Unlike a regular function, which runs completely and returns once, a generator function pauses at each yield, remembering its exact state, and resumes right there the next time a value is requested — making it a convenient way to build an iterator without writing a full class.
#how it works
1
Use yield instead of return
Anywhere in a function’s body, this marks it as a generator function.
2
Calling it returns a generator object
The function’s code doesn’t run immediately.
3
next() runs until the first yield
Then pauses there, returning that value.
4
The next call resumes exactly where it left off
Running until the next yield, or the function’s natural end.
5
Finishing raises StopIteration automatically
Exactly like a regular iterator, once there’s no more to yield.
#example
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(3):
print(number)
Output
1
2
3
1count_up_to(3) doesn’t run any code yet when called — it immediately returns a generator object.
2The for loop calls next() on it behind the scenes: the function runs until yield count, pausing there and producing 1.
3Each subsequent next() call resumes right after that yield, incrementing count, checking the while condition again, and yielding the next value.
4Once count exceeds n, the while loop ends and the function finishes naturally, which raises StopIteration and ends the for loop cleanly.
#use cases
Processing a huge or effectively infinite sequence without holding every value in memory at once, unlike building a full list up front
Writing an iterator's logic far more simply than a full class with __iter__ and __next__
Reading a large file line by line, lazily, without loading the entire file into memory
Building a data-processing pipeline where each stage is a generator, passing values through one at a time
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free →Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →