In Python what are iterators?
Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
An iterator in Python is an object that represents a stream of data. It implements the Python Iterator Protocol, which consists of two core magic methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next item from the sequence. When no elements remain, it raises theStopIterationexception.
### Custom Iterator Example:
class CountUpTo:
def __init__(self, max_value):
self.max_value = max_value
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current <= self.max_value:
val = self.current
self.current += 1
return val
raise StopIteration
counter = CountUpTo(3)
for num in counter:
print(num) # Prints 1, 2, 3
### Iterable vs Iterator:
- An Iterable is any object that can return an iterator via
iter(obj)(e.g. lists, tuples, dicts, strings). - An Iterator is the stateful helper that actually produces values one at a time via
next(it).
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.