Iterator Protocol in Python
Level 4225 keystrokes
CountUp implements the iterator protocol: __iter__ returns the object itself and __next__ returns the next number or raises StopIteration at the limit. A for loop over CountUp(3) prints 1, 2 and 3.
Python code
# A custom iterator that counts from 1 up to limit1class CountUp: # Receives the upper limit when the object is created2 def __init__(self, limit): # Stores the limit, 3 in this example3 self.limit = limit # The counter starts at 0, before the first value4 self.n = 0 # for calls __iter__ once to get the iterator5 def __iter__(self): # The object is its own iterator, so it returns self6 return self # for calls __next__ repeatedly to get each value7 def __next__(self): # Checks whether the counter has reached the limit8 if self.n >= self.limit: # StopIteration tells the for loop to stop9 raise StopIteration # Advances the counter to the next number10 self.n += 1 # Returns the new value: 1, then 2, then 311 return self.n12 # The for loop drives the iterator until StopIteration13for i in CountUp(3): # Prints 1, 2 and 3, one per line14 print(i)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:× 6.× 6(× 5)× 5=× 4,× 1+× 1>× 1