Advanced Iteration

Python IterationFree Lesson

Advertisement

Advanced Iteration

Custom iterators, iterables, and iteration patterns.

Overview

Master advanced iteration techniques.

Custom Iterators

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

for num in CountDown(5):
    print(num, end=" ")
# 5 4 3 2 1

# Fibonacci iterator
class Fibonacci:
    def __init__(self, max_count):
        self.max_count = max_count
        self.count = 0
        self.a, self.b = 0, 1
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.count >= self.max_count:
            raise StopIteration
        self.count += 1
        self.a, self.b = self.b, self.a + self.b
        return self.a

fib = Fibonacci(10)
print(list(fib))  # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Iterables

class Sentence:
    def __init__(self, text):
        self.text = text
        self.words = text.split()
    
    def __getitem__(self, index):
        return self.words[index]
    
    def __len__(self):
        return len(self.words)
    
    def __iter__(self):
        for word in self.words:
            yield word

sentence = Sentence("Hello world this is Python")
for word in sentence:
    print(word, end=" ")

Practice

Implement a tree iterator for depth-first traversal.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement