153. Implementing Custom Iterators
Here are 10 Python snippets demonstrating how to implement custom iterators to control iteration behavior. Each snippet is separated by a delimiter.
Snippet 1: Basic Custom Iterator
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
self.current += 1
return self.current - 1
# Usage
for number in Counter(1, 5):
print(number) # Output: 1, 2, 3, 4Snippet 2: Iterator for Fibonacci Sequence
Snippet 3: Reverse Iterator
Snippet 4: Custom Range Iterator
Snippet 5: Circular Iterator
Snippet 6: File Line Iterator
Snippet 7: Infinite Iterator
Snippet 8: Skipping Iterator
Snippet 9: Countdown Iterator
Snippet 10: Batched Iterator
Last updated