What are Iterators in Python?
Learn what Python iterators are, how __iter__, __next__ and StopIteration work, iterable vs iterator differences, and how to build one with clear code examples.
Expected Interview Answer
An iterator in Python is an object that produces values one at a time and remembers its position, implementing __iter__ (returns itself) and __next__ (returns the next value or raises StopIteration when exhausted).
Any object you can loop over with for is an iterable; calling iter() on it returns an iterator. The for loop repeatedly calls next() on that iterator and stops cleanly when StopIteration is raised. Iterators are lazy — they compute values on demand rather than building the whole sequence in memory — which is why generators, files, and range work efficiently over huge or infinite streams.
- Lazy, memory-efficient iteration over large or infinite data
- Uniform for-loop interface across lists, files, dicts and generators
- Encapsulates traversal state inside the object
- Enables pipelines with itertools without materializing intermediate lists
- Lets you model streams that never fully fit in memory
AI Mentor Explanation
An iterator is like a scoreboard operator who reveals the match ball by ball rather than handing you the full scorecard at once. Each 'next ball' request gives exactly one delivery, and the operator remembers which over you are on. When the innings ends, they signal 'all out' — the equivalent of raising StopIteration so you know to stop asking.
Step-by-Step Explanation
Step 1
Get an iterable
Start with any object that can be looped over, such as a list, string, dict, file or range.
Step 2
Call iter()
Passing the iterable to iter() invokes its __iter__ method and returns a fresh iterator positioned before the first item.
Step 3
Call next() repeatedly
Each next() call invokes __next__, returning the next value and advancing the internal position.
Step 4
Handle StopIteration
When there are no items left, __next__ raises StopIteration; a for loop catches this automatically and ends.
Step 5
Build your own
Define a class with __iter__ returning self and __next__ producing values, or use a generator function with yield for a shortcut.
What Interviewer Expects
- Clear distinction between an iterable and an iterator
- Knowledge of __iter__ and __next__ and the StopIteration protocol
- Understanding that iterators are lazy and stateful
- Awareness that a generator is a concise iterator
- Ability to write a custom iterator class
Common Mistakes
- Confusing an iterable with an iterator (a list is iterable but not an iterator)
- Forgetting that __iter__ on an iterator must return self
- Not raising StopIteration to signal exhaustion
- Assuming an iterator can be reused after it is exhausted
- Believing iterators load all data into memory upfront
Best Answer (HR Friendly)
“An iterator is Python's way of walking through a collection one item at a time, remembering where it left off. Instead of loading everything into memory at once, it hands you the next value only when you ask, which is efficient for large or streaming data.”
Code Example
# Any iterable can produce an iterator
nums = [10, 20, 30]
it = iter(nums) # get the iterator
print(next(it)) # 10
print(next(it)) # 20
print(next(it)) # 30
# next(it) now raises StopIteration
# A custom iterator that counts up to a limit
class CountUp:
def __init__(self, limit):
self.current = 0
self.limit = limit
def __iter__(self):
return self # an iterator returns itself
def __next__(self):
if self.current >= self.limit:
raise StopIteration
self.current += 1
return self.current
for n in CountUp(3):
print(n) # 1, 2, 3Follow-up Questions
- What is the difference between an iterable and an iterator?
- How is a generator related to an iterator?
- Why does __iter__ on an iterator return self?
- How would you create an infinite iterator safely?
- What role does the itertools module play with iterators?
MCQ Practice
1. Which two methods must an object implement to be an iterator?
An iterator implements __iter__ (returning itself) and __next__ (returning the next value or raising StopIteration).
2. What happens when next() is called on an exhausted iterator?
Once no items remain, __next__ raises StopIteration, which a for loop catches to end iteration cleanly.
3. Which statement about a Python list is correct?
A list is iterable — iter(list) returns a separate list_iterator — but the list itself has no __next__ method.
Flash Cards
What is an iterator? — An object implementing __iter__ and __next__ that yields values one at a time and tracks its position.
Iterable vs iterator? — An iterable can produce an iterator via iter(); an iterator actually yields items via next() and holds state.
How does a loop know to stop? — __next__ raises StopIteration when exhausted; the for loop catches it and ends.
Why are iterators memory efficient? — They compute values lazily on demand instead of building the entire sequence up front.