Iterators in Python
Iterators
Section titled “Iterators”Introduction
Section titled “Introduction”An iterator is an object that produces a sequence of values one at a time. Python’s for loop works by calling next() on an iterator until it raises StopIteration.
Iterator Protocol
Section titled “Iterator Protocol”flowchart TB Iterable["📦 Iterablehas __iter__()list, tuple, str, dict"] -->|"iter(iterable)"| Iterator["🔄 Iteratorhas __iter__() + __next__()remembers its position"] Iterator -->|"next(iterator)"| Value["📤 Returns next value1, 2, 3, ..."] Value -->|"More values?"| Iterator Value -->|"No more values!"| Stop["⛔ StopIterationException raised"]
style Iterable fill:#7c3aed,color:#fff style Iterator fill:#4f46e5,color:#fff style Value fill:#059669,color:#fff style Stop fill:#dc2626,color:#fffThe Iteration Protocol
Section titled “The Iteration Protocol”# An object is iterable if it has __iter__() that returns an iterator# An object is an iterator if it has __next__() that returns values
numbers = [1, 2, 3]it = iter(numbers) # Same as numbers.__iter__()
print(next(it)) # 1print(next(it)) # 2print(next(it)) # 3# print(next(it)) # StopIteration!Custom Iterator
Section titled “Custom Iterator”class Countdown: def __init__(self, start): self.start = start
def __iter__(self): self.current = self.start return self
def __next__(self): if self.current <= 0: raise StopIteration value = self.current self.current -= 1 return value
for num in Countdown(5): print(num) # 5, 4, 3, 2, 1Built-in Iterators
Section titled “Built-in Iterators”# enumerate — indexed iterationfor i, char in enumerate("hello"): print(i, char)
# zip — parallel iterationfor a, b in zip([1, 2, 3], ['a', 'b', 'c']): print(a, b)
# reversed — reverse iterationfor char in reversed("hello"): print(char)
# iter with sentineldef read_until_empty(): while True: line = input("> ") if line == "": break yield line
# itertools modulefrom itertools import cycle, chain, islice, count
# Infinite cyclecolors = cycle(["red", "green", "blue"])for _ in range(6): print(next(colors)) # red, green, blue, red, green, blue
# Chain iterablescombined = chain([1, 2, 3], ['a', 'b', 'c'])print(list(combined)) # [1, 2, 3, 'a', 'b', 'c']
# Infinite countfor i in islice(count(10, 2), 5): print(i) # 10, 12, 14, 16, 18Best Practices
Section titled “Best Practices”- Use iterators for large datasets — they’re memory-efficient
- Use
iter()andnext()for manual iteration control - Use
itertoolsfor common iteration patterns - Know when an iterator is exhausted — you can’t reset it
Practice Exercises
Section titled “Practice Exercises”Exercise 1: Create an iterator that generates Fibonacci numbers up to a limit.
Exercise 2: Implement an iterator that reads a file in chunks of N bytes.