Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.
Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβperfect for learners of all ages.
Enroll to start learning
Youβve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take mock test.
return self
def __next__(self):
if self.current <= 0:
# End iteration when countdown finishes
raise StopIteration
else:
# Return current value and decrement
value = self.current
self.current -= 1
return value
cd = CountDown(3)
for number in cd:
print(number)
Output:
3
2
1
Explanation
init(self, start): Initializes the countdown start value.
iter(self): Returns the iterator object (self) so it can be used in iteration contexts.
next(self): Returns the current value and decrements it. Raises StopIteration when the countdown is over.
The for loop internally calls these methods to retrieve values until the sequence ends.
Real-Life Analogy
Think of a countdown timer at a race start. Each tick reduces the timer by one. Once the timer hits zero, it stopsβjust like the StopIteration ends the iteration.
Audio Book Style Summary
Chunk Title: Creating Custom Iterators
Chunk Text: Custom iterators in Python are classes that implement iter() and next() methods to produce values one by one.
Detailed Explanation: By defining these methods, you control exactly how your object yields data during iteration, including managing when iteration should stop.
Analogy: Like a countdown timer that ticks down one number at a time until zero.
Key Concepts
Custom Iterator: A user-defined class that implements the iterator protocol.
Internal State: Variables inside the iterator that track progress.
StopIteration: Signals that the iterator has no more data to yield.
Estimated Study Time
20 minutes
Glossary
Iterator Protocol: Rules an iterator follows (iter() and next()).
StopIteration: Exception to indicate iteration completion.
Internal State: The position or data the iterator keeps track of during iteration.
Practice Exercise
Implement a custom iterator class EvenNumbers that iterates over even numbers from 2 up to a given limit.
Reference Links
Python Iterator Protocol
Real Python: Iterator Tutorial
Programiz: Python Iterators
Exercises
Easy
Question: What are the two key methods a custom iterator class must implement?
Answer: iter() and next()
Hint: Think about how Python knows to get the next item and where the iteration starts.
Question: What happens when next() raises a StopIteration exception?
Answer: It signals that the iteration is complete and no more items are left to return.
Hint: This stops the loop or any iteration from continuing.
Medium
Question: How would you implement the iter() method in a custom iterator class?
Answer: It should return the iterator object itself, usually return self.
Hint: This method allows the object to be used in loops.
Question: In the custom CountDown iterator example, why is the current value decreased before returning?
Answer: To move the iterator closer to the stopping condition and return the correct countdown number.
Hint: Think about how the countdown sequence works.
Hard
Question: Write a custom iterator class that iterates over the first N even numbers. Outline the main methods and logic.
Answer: The class would store N and a current count. iter() returns self. next() increments the current even number and stops when count exceeds N, raising StopIteration.
Hint: Remember to maintain internal state and stop correctly.
Question: Explain why maintaining internal state inside the iterator is critical for custom iterators and how it affects iteration.
Answer: Internal state keeps track of the current position or value to yield the next item properly without restarting. This allows efficient, sequential access without holding the entire sequence in memory.
Hint: Think about why you donβt want to generate the whole sequence upfront.
Quiz
Question: What should the iter() method return in a custom iterator?
Type: mcq
Options: self, None, next()
Correct Answer: self
Explanation: iter() returns the iterator object itself, allowing it to be used in a loop.
Hint: It connects the iterable to the iterator.
Question: True or False: You can use a custom iterator multiple times without reinitializing it.
Type: boolean
Options: True, False
Correct Answer: False
Explanation: Once exhausted, the iterator cannot restart unless reinitialized or a new iterator is created.
Hint: Iterators maintain their position and do not reset automatically.
Challenge Problems
Problem: Create a custom iterator that yields the squares of numbers from 1 up to a given limit.
Solution: Implement a class with internal state tracking the current number. In next(), return the square and increment until the limit, then raise StopIteration.
Hint: Use current to keep track and stop at the limit.
Problem: Design a custom iterator that generates the factorial of numbers starting from 1 indefinitely. (Hint: infinite iterator)
Solution: Keep track of the current number and current factorial value. Each call to next() computes the next factorial by multiplying by the current number and increments it, never raising StopIteration.
Hint: This iterator doesnβt stop, so be careful when using it.