Spex3
    

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