Skip to main content

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.

L1

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 obj calls iter(obj) to get an iterator, then repeatedly calls next until StopIteration.
  • Real life: a playlist is iterable; the playhead that moves song-by-song is the iterator.
  • Test with collections.abc.Iterable or try iter(obj) — if it fails with TypeError, 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 with next.
  • 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 returns it itself, so you can for-loop it — but only once.
PointIterableIterator
Protocol__iter__ returns an iterator__next__ returns the next value
ReuseCan create many independent iteratorsUsually one-shot; exhausted after use
Exampleslist, str, dict, rangeiter([1,2]), file object, generator
for loopCalls iter firstUses next until StopIteration
Real lifeThe bookshelfYour finger moving book by book

iter() and next()

  • iter(obj) asks for an iterator. next(it) pulls one value; when finished it raises StopIteration.
  • next(it, default) returns default instead of raising when the iterator is exhausted — handy for optional pulls.
  • Manually driving next is how for works 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) returning self (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 yield is a generator function. Calling it returns a generator object — it does not run the body yet.
  • Each next(gen) runs until the next yield, 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.
ApproachMemoryReuseTypical use
List / comprehensionHolds all itemsMany passesSmall/medium data you index
Generator / genexpOne item (plus state)One passLarge files, streams, pipelines
range (Python 3)O(1) objectMany passesIndex loops without a giant list
L2

Advanced — Iterators & Generators

send, throw, and close

  • gen.send(value) resumes the generator and makes yield express that value on the right-hand side.
  • The first resume must be next(gen) or gen.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() raises GeneratorExit so 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 subgen delegates to another iterable/generator, forwarding send/throw and returning the subgenerator’s return value.
  • It replaces manual loops of for x in sub: yield x and is the building block for generator-based coroutines (historically).
  • A generator can return value; that value becomes the result of yield from (and appears on StopIteration.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

  • itertools builds 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.
  • tee splits 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 StopIteration forever after; create a new generator to replay.
  • Do not mutate a list while iterating it with a for loop — collect indices/items to change, or iterate a copy.
  • Returning a list from a function that could yield forces full materialisation — prefer generators at API boundaries for large data.

Iterator vs generator — design choice

NeedPrefer
Simple sequence logicyield generator function
Rich object with methods / reuse rulesCustom class with __iter__ / __next__
One-liner transformGenerator expression
Combinatorics / infinite countersitertools
Multiple independent passesMaterialise to list/tuple, or recreate iterator
L3

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.

L4

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))
L5

Problem Solving Tricks

  • Prefer next(it, None) when a missing value is normal — avoid bare try/except StopIteration noise.
  • list(gen) and tuple(gen) consume the generator; keep a reference only if you still need it unconsumed.
  • Files are iterators: for line in open(...) streams lines — still prefer with open(...).
  • enumerate, zip, reversed, and map return iterators (lazy) in Python 3.
  • Use itertools.chain.from_iterable to flatten one level without recursion.
  • Generator return values only surface via yield from or StopIteration.value — beginners often miss this.
  • Do not mix send with plain next carelessly; after the first next, drive with send if you use two-way flow.
  • range is 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.
L6

Practice Programs List

  1. Write a generator that yields only prime numbers below N.
  2. Implement a reusable Range class with __iter__ returning a fresh iterator each time.
  3. Build a CSV line reader generator that skips blank lines and strips whitespace.
  4. Rewrite a list-based map/filter pipeline as chained generator expressions and compare memory for a large range.
  5. Use yield from to merge three generators in round-robin fashion with itertools.cycle of iterators.
  6. Add send support to a generator that accumulates min and max of streamed numbers.
  7. Explain in comments why tee can use a lot of memory if one branch lags.
  8. Convert a recursive tree walk into a generator that yields node values depth-first.