🐍 Python Intermediate

What is Python's iterator protocol?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

An iterator is an object implementing two methods: __iter__() (returns self) and __next__() (returns the next value, raises StopIteration when exhausted). An iterable is an object implementing __iter__() that returns an iterator (lists, dicts, sets are iterable but not iterators themselves). for item in iterable calls iter(iterable) to get an iterator, then calls next() until StopIteration. Custom iterator: class Counter: def __init__(self, max): self.n = 0; self.max = max; def __iter__(self): return self; def __next__(self): if self.n >= self.max: raise StopIteration; self.n += 1; return self.n. The itertools module provides tools for working with iterators: chain(), cycle(), islice(), takewhile(), groupby().

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Python candidates.