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 limit
1class CountUp:
# Receives the upper limit when the object is created
2 def __init__(self, limit):
# Stores the limit, 3 in this example
3 self.limit = limit
# The counter starts at 0, before the first value
4 self.n = 0
# for calls __iter__ once to get the iterator
5 def __iter__(self):
# The object is its own iterator, so it returns self
6 return self
# for calls __next__ repeatedly to get each value
7 def __next__(self):
# Checks whether the counter has reached the limit
8 if self.n >= self.limit:
# StopIteration tells the for loop to stop
9 raise StopIteration
# Advances the counter to the next number
10 self.n += 1
# Returns the new value: 1, then 2, then 3
11 return self.n
12
# The for loop drives the iterator until StopIteration
13for i in CountUp(3):
# Prints 1, 2 and 3, one per line
14 print(i)

Output

1
2
3
Practice typing this code

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

More Python examples at level 4

← Python typing practice