Every generator object automatically implements the iterator protocol -- it has __iter__ (returning itself) and __next__ (resuming execution until the next yield or StopIteration on completion). Generators are the easiest way to write an iterator without manually managing state in a class.
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen), next(gen)) # 3 2
print(hasattr(gen, '__next__')) # True
Real-world example
A recursive directory walker is written as a generator function instead of a class-based iterator because yield handles the state machine automatically.
Likely follow-ups
Why is a generator function simpler than a class-based iterator for most cases?
What state does a generator preserve between yields?
groupby only groups consecutive items that share a key -- it does not sort or globally group like a SQL GROUP BY. A common mistake is calling groupby on unsorted data, which silently produces multiple separate groups for the same key value scattered through the output instead of one combined group.
import itertools
data = [('a',1), ('b',2), ('a',3)] # not sorted by key
for k, g in itertools.groupby(data, key=lambda x: x[0]):
print(k, list(g))
# Output: a [('a',1)] b [('b',2)] a [('a',3)] -- 'a' appears twice!
# Correct: sort first
for k, g in itertools.groupby(sorted(data), key=lambda x: x[0]):
print(k, list(g))
Real-world example
A report generator groups sales records by region using groupby but gets duplicate region sections until the data is sorted by region first.
Likely follow-ups
Why doesn't groupby sort automatically?
What's the time complexity difference between groupby+sort and a dict-based grouping?
Use iter() to get an iterator from an iterable, then call next() repeatedly, optionally wrapped in try/except StopIteration or with a default value, to pull and inspect values one at a time -- useful for peeking at the first item or interleaving manual logic with iteration.
data = [10, 20, 30]
it = iter(data)
first = next(it)
print('First:', first)
print('Rest:', list(it)) # [20, 30]
Real-world example
A CSV parser peeks at the first row with next(it) to detect and validate the header before processing the remaining rows with a for-loop.
Likely follow-ups
How would you 'push back' a value onto an iterator?
What's itertools.chain used for combining a peeked value with the rest?
A file object is simultaneously a context manager (via __enter__/__exit__) and an iterator (via __iter__/__next__). Using `with open(...) as f: for line in f:` combines both protocols so the file is guaranteed to close via __exit__ even if an exception interrupts the iteration midway through the for-loop.
with open('log.txt') as f:
for line in f:
if 'ERROR' in line:
process(line)
# file automatically closed here, even on exception
Real-world example
A log-tailing tool relies on this pairing to ensure file handles are always released promptly even when processing raises an unexpected exception mid-file.
Likely follow-ups
What happens if an exception occurs inside the for-loop body?
How would you write a class combining both protocols?
They are equivalent: a for-loop implicitly calls iter(obj) once to obtain an iterator, then calls next() on that iterator repeatedly until StopIteration. Calling iter() explicitly just lets you obtain and hold onto the iterator object yourself, for example to pass it to another function or advance it manually between loop iterations.
nums = [1, 2, 3]
# Implicit (for-loop does this internally)
for n in nums:
print(n)
# Explicit equivalent
it = iter(nums)
while True:
try:
print(next(it))
except StopIteration:
break
Real-world example
Understanding this equivalence helps when debugging why modifying a list during a for-loop over it produces unexpected skipped elements -- the loop is really advancing a live iterator.
Likely follow-ups
Why is mutating a list while iterating over it risky?
What does calling iter() on an already-iterator object do?