Generator Functions
A generator function uses yield instead of return. It produces a sequence of values lazily, pausing between each yield. State is preserved between calls.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(5):
print(num)
Try it Yourself โ
Generator Expressions
Generator expressions look like list comprehensions but use parentheses. They produce items one at a time without storing the whole list in memory.
squares = (x * x for x in range(10))
for s in squares:
print(s)
Try it Yourself โ