Category: python
Generator Functions
Published on 27 Oct 2026
Explanation
A function containing yield returns a generator iterator when called and produces values one at a time.
Code:
def numbers():
yield 10
yield 20
yield 30
g = numbers()
print(next(g), next(g), next(g))
Explanation
At yield, execution pauses and local state is retained until the next value is requested.
Code:
def demo():
print('Start')
yield 10
print('Resume')
yield 20
g = demo()
print(next(g))
print(next(g))
Explanation
Generators can calculate sequences incrementally rather than storing the full result list.
Code:
def squares(limit):
for n in range(limit): yield n * n
print(list(squares(5)))
Explanation
When a generator finishes, iteration ends with StopIteration. for loops handle this automatically.
Code:
def values():
yield 'A'
yield 'B'
g = values()
print(next(g), next(g), next(g, 'Finished'))
Explanation
A generator can process a file line by line without loading all lines into memory at once.
Code:
def read_numbers(filename):
with open(filename, encoding='utf-8') as file:
for line in file:
line = line.strip()
if line: yield int(line)
# for n in read_numbers('numbers.txt'): print(n)