By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Iterators are fundamental constructs in Python that allow you to traverse through all the elements of a collection, regardless of its type. Mastering iterators, iter(), and next() is crucial for efficient data processing and memory management. Understanding how to build custom iterators enables you to create flexible and reusable code. In real-world applications, iterators are used in data pipelines, file handling, and more. Misunderstanding this concept can lead to inefficient code, memory leaks, and bugs that are hard to diagnose. For example, improperly handling an iterator can cause an infinite loop, crashing your application.
Pitfall: Not implementing both methods will break the iterator.
Using iter() and next()
python my_list = [1, 2, 3] my_iter = iter(my_list) print(next(my_iter)) # Output: 1
Pitfall: Calling next() on an exhausted iterator raises StopIteration.
Building a Custom Iterator
Example: ```python class Counter: def init(self, low, high): self.current = low self.high = high
def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1
``` - Pitfall: Forgetting to raise StopIteration will cause an infinite loop.
Iterating Over Custom Iterators
python counter = Counter(1, 3) for number in counter: print(number) # Output: 1 2 3
Experts view iterators as a way to abstract the iteration logic, making code more modular and reusable. They think in terms of data streams and pipelines, where each component can be an iterator processing data in a specific way. This perspective allows for more flexible and maintainable code.
Exam trap: Questions that require identifying valid iterators.
The mistake: Not raising StopIteration.
Exam trap: Code snippets that omit StopIteration.
The mistake: Modifying the iterator state externally.
Exam trap: Scenarios involving external state changes.
The mistake: Using next() without checking for StopIteration.
Scenario: You need to create an iterator that yields Fibonacci numbers up to a given limit. Question: Implement the iterator and use it to print the first 10 Fibonacci numbers. Solution:
class Fibonacci: def __init__(self, limit): self.limit = limit self.a, self.b = 0, 1 self.count = 0 def __iter__(self): return self def __next__(self): if self.count >= self.limit: raise StopIteration self.count += 1 self.a, self.b = self.b, self.a + self.b return self.a fib = Fibonacci(10) for number in fib: print(number)
Answer: The output will be the first 10 Fibonacci numbers. Why it works: The iterator correctly implements the Fibonacci sequence and stops after the given limit.
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.