Python Iterator vs Generator: Understanding the Design Pattern

🐍 Python Interview Question: Iterator vs Generator Seems simple, right? But there's more depth here than most candidates realize. The Python answer: An iterator is any object implementing iter() and next(). A generator is a function containing yield — calling it returns a generator object. Every generator IS an iterator (collections.abc.Generator is a subclass of Iterator), but not every iterator is a generator. Where it gets interesting — the CS perspective: The Iterator is a GoF (Gang of Four) behavioral design pattern. It defines TWO distinct roles: • Aggregate — the collection that holds data (list, tree, graph) • Iterator — a separate object that traverses the Aggregate without exposing its internal structure This separation follows the encapsulation principle from OOP: clients iterate through elements without knowing if the underlying structure is an array, linked list, or hash map. Now here's the tricky part: In classic CS, an Iterator always traverses an existing data structure. A Generator is conceptually different — it COMPUTES the next value on demand. There may be no data structure at all. Think of Fibonacci numbers or infinite sequences. Python blurs this line intentionally. You can build an iterator class with next() that generates values without any backing collection (like range()). You can also use yield to lazily walk through an actual data structure. Python's iterator protocol is more general than the GoF pattern. The hierarchy in collections.abc makes this clear: • Iterable — has iter() • Iterator — adds next()    • Generator — adds send(), throw(), close() • Collection — has contains(), iter(), len()   • Sequence — adds getitem() (indexing) The interview-winning insight: Python's "iterator" is broader than the CS design pattern. The GoF Iterator requires an Aggregate. Python's iterator protocol doesn't — it's just "anything that can produce a next value." Generators are the purest expression of this: no collection, no structure, just lazy computation. Next time someone asks "what's the difference between a generator and an iterator?" — don't just recite iter and next. Show them you understand the design pattern behind it. 🎯 #Python #SoftwareEngineering #InterviewTips #DesignPatterns #OOP

  • No alternative text description for this image

One of the default interview questions)

To view or add a comment, sign in

Explore content categories