Iterators
An iterator is any object that lets you traverse a sequence of values one at a time. Python's for loop, list comprehensions, and many built-in functions al...
Building and Using Iterators in Python
An iterator is any object that lets you traverse a sequence of values one at a time. Python's for loop, list comprehensions, and many built-in functions all work by using iterators under the hood. Understanding iterators helps you write memory-efficient code and build your own custom sequences.
Python uses two related concepts: iterables and iterators. An iterable is anything you can loop over, such as a list, string, or dictionary. When you use a for loop, Python calls the __iter__ method on the iterable to get an iterator, then repeatedly calls __next__ on that iterator until it raises StopIteration.
You can build a custom iterator by defining a class with both __iter__ and __next__ methods:
class CountDown: def __init__(self, start): self.current = start
def __iter__(self): return self
def __next__(self): if self.current <= 0: raise StopIteration value = self.current self.current -= 1 return value
for number in CountDown(5): print(number) # prints 5, 4, 3, 2, 1
The __iter__ method returns the iterator itself, which allows the object to be used directly in a for loop. The __next__ method returns the next value each time it is called. When there are no more values, it raises StopIteration to signal the loop to stop.
A simpler way to create an iterator in Python is to use a generator function. Instead of building a class, you write a function that uses the yield keyword. Each time the generator is called with next(), it resumes from where it left off. Generators are lazy, meaning they produce values one at a time without storing all of them in memory.
def count_down(start): while start > 0: yield start start -= 1
for number in count_down(5): print(number)
This produces the same output with far less code. Generators are especially useful when working with large data sets that would be expensive to load all at once.
Interview tip: Be ready to explain the difference between an iterable and an iterator. An iterable has __iter__ but may not have __next__. An iterator has both. All iterators are iterables, but not all iterables are iterators. A list is an iterable but not an iterator. Calling iter() on a list returns a list_iterator, which is the actual iterator.