Python › Comprehensions & Generators
What is a generator function, and how does 'yield' make it different from a regular function?
BeginnerAnswer
A generator function contains at least one 'yield' statement; calling it doesn't run the function body immediately — it returns a generator object, and the body only executes incrementally, one step at a time, each time you request the next value (via next() or a for loop).
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for number in count_up_to(3):
print(number) # 1, 2, 3Real-world example Lazily producing a sequence of values one at a time instead of building and returning a full list upfront.