Advanced Python
Iterators & Generators
Complete lesson for Iterators & Generators using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Iterators & Generators
Section: Advanced Python. Walk sequences one item at a time with iterators, then write lazy pipelines with yield, generator expressions, and itertools.
What is an iterable?
- An iterable is any object you can loop over with
for— lists, tuples, strings, dicts, sets, files, and many custom types. - Internally,
for x in objcallsiter(obj)to get an iterator, then repeatedly callsnextuntilStopIteration. - Real life: a playlist is iterable; the playhead that moves song-by-song is the iterator.
- Test with
collections.abc.Iterableor tryiter(obj)— if it fails withTypeError, it is not iterable.
nums = [10, 20, 30]
for n in nums:
print(n)
print("done") Iterable vs iterator
- An iterable can produce an iterator via
iter(x). An iterator is the object that actually yields values withnext. - Most containers are iterable but not their own iterators: calling
iter(list)returns a new list iterator each time. - An iterator is iterable too:
iter(it)usually returnsititself, so you canfor-loop it — but only once.
| Point | Iterable | Iterator |
|---|---|---|
| Protocol | __iter__ returns an iterator | __next__ returns the next value |
| Reuse | Can create many independent iterators | Usually one-shot; exhausted after use |
| Examples | list, str, dict, range | iter([1,2]), file object, generator |
for loop | Calls iter first | Uses next until StopIteration |
| Real life | The bookshelf | Your finger moving book by book |
iter() and next()
iter(obj)asks for an iterator.next(it)pulls one value; when finished it raisesStopIteration.next(it, default)returnsdefaultinstead of raising when the iterator is exhausted — handy for optional pulls.- Manually driving
nextis howforworks under the hood.
it = iter(["a", "b", "c"])
print(next(it))
print(next(it))
print(next(it))
print(next(it, "END")) Custom iterator class
- Implement
__iter__(self)returningself(or a fresh iterator) and__next__(self)returning the next value. - When there are no more values, raise
StopIteration— do not return a sentinel unless that is your API. - Keep state on the instance (
self.index,self.n) so each call to__next__advances.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) Generator functions with yield
- A function that contains
yieldis a generator function. Calling it returns a generator object — it does not run the body yet. - Each
next(gen)runs until the nextyield, pauses, and resumes later with local state intact. - Generators are iterators: they implement
__iter__and__next__for you. - Use them for large or infinite sequences without building a full list in memory.
def countdown(n):
while n > 0:
yield n
n -= 1
g = countdown(3)
print(next(g), next(g), next(g))
print(list(countdown(4))) Generator expressions
(x * x for x in range(5))is a generator expression — like a list comprehension but lazy.- Use
[]when you need random access or multiple passes; use()when you stream once. - Passing a genexp to a function that takes one iterable often drops the outer parentheses:
sum(x*x for x in range(5)).
squares = (n * n for n in range(1, 6))
print(list(squares))
print(sum(n * n for n in range(1, 6))) Why lazy evaluation matters
- Lists store every element; generators compute on demand and can represent infinite streams.
- Pipelines of generators compose: filter → map → take, without intermediate giant lists.
- Files are already lazy iterators over lines — pair them with generators for clean ETL-style code.
| Approach | Memory | Reuse | Typical use |
|---|---|---|---|
| List / comprehension | Holds all items | Many passes | Small/medium data you index |
| Generator / genexp | One item (plus state) | One pass | Large files, streams, pipelines |
range (Python 3) | O(1) object | Many passes | Index loops without a giant list |
Advanced — Iterators & Generators
send, throw, and close
gen.send(value)resumes the generator and makesyieldexpress that value on the right-hand side.- The first resume must be
next(gen)orgen.send(None)— you cannot send a non-None value into a brand-new generator. gen.throw(exc)injects an exception at the pause point;gen.close()raisesGeneratorExitso cleanup (finally) can run.
def echo():
got = yield "ready"
while True:
got = yield f"got:{got}"
g = echo()
print(next(g))
print(g.send("hi"))
print(g.send(99))
g.close() yield from and subgenerators
yield from subgendelegates to another iterable/generator, forwardingsend/throwand returning the subgenerator’s return value.- It replaces manual loops of
for x in sub: yield xand is the building block for generator-based coroutines (historically). - A generator can
return value; that value becomes the result ofyield from(and appears onStopIteration.value).
def pair():
yield "a"
yield "b"
return "done-pair"
def wrap():
result = yield from pair()
yield f"sub:{result}"
print(list(wrap())) itertools essentials
itertoolsbuilds fast, memory-efficient iterators:count,cycle,repeat,chain,islice,tee,groupby,product,permutations,combinations.islice(it, stop)takes a prefix without converting the whole stream to a list.teesplits one iterator into several — but buffering can grow if consumers advance unevenly.
import itertools
print(list(itertools.islice(itertools.count(10, 2), 5)))
print(list(itertools.chain([1, 2], (3, 4), "ab")))
print(list(itertools.combinations("ABC", 2))) Stateful iterators and pitfalls
- Exhausted generators raise
StopIterationforever after; create a new generator to replay. - Do not mutate a list while iterating it with a
forloop — collect indices/items to change, or iterate a copy. - Returning a list from a function that could
yieldforces full materialisation — prefer generators at API boundaries for large data.
Iterator vs generator — design choice
| Need | Prefer |
|---|---|
| Simple sequence logic | yield generator function |
| Rich object with methods / reuse rules | Custom class with __iter__ / __next__ |
| One-liner transform | Generator expression |
| Combinatorics / infinite counters | itertools |
| Multiple independent passes | Materialise to list/tuple, or recreate iterator |
Tricky Interview Points
Q1) What is the difference between an iterable and an iterator?
Answer An iterable implements __iter__ and can produce an iterator. An iterator implements __next__ (and usually __iter__ returning itself) and yields values until StopIteration.
Q2) What does the for-loop do internally?
Answer It calls iter(obj), then repeatedly next(iterator) until StopIteration, which ends the loop silently.
Q3) What is a generator?
Answer A lazy iterator created by a generator function (uses yield) or a generator expression. It produces values on demand and keeps local state between yields.
Q4) List comprehension vs generator expression?
Answer List comprehensions build a full list in memory. Generator expressions are lazy and one-shot, better for large or streamed data.
Q5) What is StopIteration?
Answer The exception an iterator raises when exhausted. for-loops catch it; bare next(it) surfaces it unless you pass a default.
Q6) Can you restart a generator?
Answer No. Once exhausted, call the generator function again to get a fresh generator object.
Q7) What does yield from do?
Answer It delegates iteration to a sub-iterable/generator, forwarding send/throw, and can capture the subgenerator return value.
Q8) How do you make a custom iterable class?
Answer Define __iter__ that returns an iterator. Either return self with __next__, or return a separate iterator object so the container stays reusable.
Q9) Why are generators memory efficient?
Answer They compute one value at a time instead of storing the whole sequence, so peak memory stays low for large or infinite streams.
Q10) What is itertools.islice used for?
Answer Taking a slice of any iterable without converting it to a list first — useful for prefixes of infinite or huge iterators.
Q11) What happens if __next__ never raises StopIteration?
Answer The iterator is infinite. A for-loop will run forever unless you break, islice, or otherwise stop.
Q12) Are dictionaries iterable?
Answer Yes. Iterating a dict yields keys. Use .values() or .items() for values or pairs. In Python 3.7+ insertion order is preserved.
Simple Programs
Fibonacci generator
def fib(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
print(list(fib(50))) Chunk a list with a generator
def chunks(seq, size):
for i in range(0, len(seq), size):
yield seq[i : i + size]
print(list(chunks([1, 2, 3, 4, 5, 6, 7], 3))) Running average with send
def running_avg():
total = 0.0
count = 0
avg = None
while True:
value = yield avg
total += value
count += 1
avg = total / count
ra = running_avg()
next(ra)
print(ra.send(10))
print(ra.send(20))
print(ra.send(30)) Flatten nested lists
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4], 5], 6]))) Pipeline with generator expressions
nums = range(1, 21)
evens = (n for n in nums if n % 2 == 0)
squares = (n * n for n in evens)
print(list(squares)) Problem Solving Tricks
- Prefer
next(it, None)when a missing value is normal — avoid baretry/except StopIterationnoise. list(gen)andtuple(gen)consume the generator; keep a reference only if you still need it unconsumed.- Files are iterators:
for line in open(...)streams lines — still preferwith open(...). enumerate,zip,reversed, andmapreturn iterators (lazy) in Python 3.- Use
itertools.chain.from_iterableto flatten one level without recursion. - Generator return values only surface via
yield fromorStopIteration.value— beginners often miss this. - Do not mix
sendwith plainnextcarelessly; after the firstnext, drive withsendif you use two-way flow. rangeis not a generator, but it is a lazy immutable sequence — cheap and reusable.- Name generator functions with verbs (
iter_lines,generate_ids) so call sites look like factories. - For debugging, wrap with
list(...)temporarily; remove materialisation before production on big data.
Practice Programs List
- Write a generator that yields only prime numbers below N.
- Implement a reusable
Rangeclass with__iter__returning a fresh iterator each time. - Build a CSV line reader generator that skips blank lines and strips whitespace.
- Rewrite a list-based map/filter pipeline as chained generator expressions and compare memory for a large range.
- Use
yield fromto merge three generators in round-robin fashion withitertools.cycleof iterators. - Add
sendsupport to a generator that accumulates min and max of streamed numbers. - Explain in comments why
teecan use a lot of memory if one branch lags. - Convert a recursive tree walk into a generator that yields node values depth-first.