Hackforge Academy

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)

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community