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 iterated
1class Range:
# Constructor takes start and end values
2 def __init__(self, start, end):
3 self.start = start
4 self.end = end
5
# __iter__ is called when iteration begins
6 def __iter__(self):
# Initialize current position to start
7 self.current = self.start
# Return self as the iterator object
8 return self
9
# __next__ is called for each iteration
10 def __next__(self):
# Stop when current reaches end (end is exclusive)
11 if self.current >= self.end:
12 raise StopIteration
# Save current value before incrementing
13 val = self.current
14 self.current += 1
# Return the saved value
15 return val
16
# Use the custom iterator in a for loop
17for n in Range(1, 4):
18 print(n)

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
  • .× 8
  • :× 6
  • =× 6
  • (× 5
  • )× 5
  • ,× 3
  • +× 1
  • >× 1

More Python examples at level 5

← Python typing practice