Hackforge Academy

Category: python

Iterator and Generator Concepts

Published on 27 Oct 2026

Explanation

An iterator implements __iter__() and __next__(). A generator is a convenient kind of iterator created by a generator function or expression.

Code:

def generate():
    yield 10
    yield 20
g = generate()
print(next(g), iter(g) is g)

Explanation

A class-based iterator maintains state and raises StopIteration when exhausted.

Code:

class Counter:
    def __init__(self, limit): self.current, self.limit = 1, limit
    def __iter__(self): return self
    def __next__(self):
        if self.current > self.limit: raise StopIteration
        value = self.current
        self.current += 1
        return value
print(list(Counter(3)))

Explanation

A generator expresses iteration logic with less boilerplate because Python manages iterator state.

Code:

def count(limit):
    for n in range(1, limit + 1): yield n
print(list(count(3)))

Explanation

Generators produce values on demand but retain local state and referenced objects needed for resumption.

Code:

def squares(limit):
    for n in range(limit): yield n * n
g = squares(1_000_000)
print(next(g), next(g), next(g))

Explanation

Use generators for straightforward lazy sequences; use a custom iterator class when a richer object model or extra methods are useful.

Code:

class Countdown:
    def __init__(self, start): self.start = start
    def __iter__(self):
        for n in range(self.start, 0, -1): yield n
print(list(Countdown(4)))

πŸš€ 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