Iterators in Python ππ

Iterators allow you to loop through elements in an efficient and memory-friendly way. They are the foundation of Pythonβs for loops and many built-in objects like lists, tuples, and dictionaries.
1οΈβ£ What is an Iterator?
An iterator is an object that implements the iterator protocol, which consists of:
β __iter__() β Returns the iterator object itself.
β __next__() β Returns the next value and raises StopIteration when done.
β
Example: Using an Iterator
numbers = iter([1, 2, 3]) # Get an iterator from a list
print(next(numbers)) # 1
print(next(numbers)) # 2
print(next(numbers)) # 3
# print(next(numbers)) # Raises StopIteration (end of sequence)
2οΈβ£ Creating a Custom Iterator
We can define our own iterators by implementing __iter__() and __next__().
β
Example: Custom Iterator that Generates Numbers Up to a Limit
class Counter:
def __init__(self, max_value):
self.max = max_value
self.current = 0 # Start from 0
def __iter__(self):
return self # The iterator object itself
def __next__(self):
if self.current < self.max:
self.current += 1
return self.current
else:
raise StopIteration # End of iteration
counter = Counter(3)
for num in counter:
print(num) # 1, 2, 3
β Implements the iterator protocol.
β Raises StopIteration when done.
3οΈβ£ Infinite Iterators
You can create infinite iterators using __next__(), but be careful with them!
β
Example: Infinite Fibonacci Iterator
class Fibonacci:
def __init__(self):
self.a, self.b = 0, 1 # Start values
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
return self.a
fib = Fibonacci()
for _ in range(5):
print(next(fib)) # 1, 1, 2, 3, 5
β Generates Fibonacci numbers indefinitely.
β Use break or islice() to limit iterations.
4οΈβ£ Using iter() with Callables
iter() can take a callable (a function) and a sentinel value (stop condition).
β
Example: Read a File Line by Line Until a Condition
with open("example.txt", "r") as file:
for line in iter(file.readline, ''): # Reads until an empty string is returned
print(line.strip())
β Efficient for reading large files.
β Uses less memory than readlines().
5οΈβ£ Summary
Concept Description
Iterator Protocol Uses __iter__() and __next__()
Built-in Iterators iter(list), iter(tuple), etc.
Custom Iterator A class with __iter__() and __next__()
Infinite Iterators Can keep generating values (e.g., Fibonacci)
iter(callable, sentinel) Iterates until a specific value appears
Date: 2025-03-24 00:00:00.000000