Custom Iterator in Python
Level 5287 keystrokes
This creates a custom iterator class implementing __iter__ and __next__. The iterator protocol allows objects to be used in for loops.
Python code
# Define a custom class that can be iterated1class Range: # Constructor takes start and end values2 def __init__(self, start, end):3 self.start = start4 self.end = end5 # __iter__ is called when iteration begins6 def __iter__(self): # Initialize current position to start7 self.current = self.start # Return self as the iterator object8 return self9 # __next__ is called for each iteration10 def __next__(self): # Stop when current reaches end (end is exclusive)11 if self.current >= self.end:12 raise StopIteration # Save current value before incrementing13 val = self.current14 self.current += 1 # Return the saved value15 return val16 # Use the custom iterator in a for loop17for n in Range(1, 4):18 print(n)Output
1 2 3
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 12.× 8:× 6=× 6(× 5)× 5,× 3+× 1>× 1