What are Iterators?

Iterators are objects that can be iterated (looped) upon. They implement the iterator protocol with __iter__() and __next__() methods.

Built-in Iterators

Many Python objects are iterable:

# Lists, tuples, strings are iterable
for item in [1, 2, 3]:
    print(item)

for char in "hello":
    print(char)

Creating Custom Iterator

Implement iterator protocol:

class CountDown:
    def __init__(self, start):
        self.current = start
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

# Use iterator
for num in CountDown(5):
    print(num)  # 5, 4, 3, 2, 1

Using iter() and next()

Manually iterate:

my_list = [1, 2, 3]
iterator = iter(my_list)

print(next(iterator))  # 1
print(next(iterator))  # 2
print(next(iterator))  # 3
# print(next(iterator))  # StopIteration

Iterator vs Iterable

  • Iterable: Has __iter__() method
  • Iterator: Has __next__() method
  • All iterators are iterables: But not all iterables are iterators

Best Practices

  • Use generators: Simpler than custom iterators
  • Implement both methods: __iter__ and __next__
  • Raise StopIteration: When iteration is complete
  • Consider itertools: For common iterator patterns

Next Steps

Learn about generators, which are simpler ways to create iterators.