Iterators & GeneratorsIntermediate
1Question 1 of 1
pythonWhat is the difference between an Iterator and an Iterable in Python?
Explanation & Concept
• Iterable: Any Python object capable of returning its members one at a time (implements `__iter__()`, e.g. list, tuple, set, dict). • Iterator: The stateful object that performs the traversal. It implements `__next__()` and raises `StopIteration` when no more elements remain.
Code Example
python
numbers = [10, 20] # Iterable
# Get the iterator
iterator = iter(numbers)
print(next(iterator)) # 10
print(next(iterator)) # 20
# next(iterator) -> Raises StopIteration!How It Works & Key Takeaways
Python's `for item in sequence:` loop under the hood calls `iter()` on the sequence and repeatedly calls `next()` until `StopIteration` is caught.
Mock Test · 1 Questions · Optional
Ready for Exception Handling?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate2 questions