Iterator Class
Completed
Write a class EvenNumbers(limit) implementing __iter__ and __next__ that produces 0, 2, 4, … up to limit (inclusive) and then raises StopIteration. Print the values on one line, then print them again (create a new iterator).
Input
One integer.
Output
Two identical lines.
Example
Input
10
Output
0 2 4 6 8 10 0 2 4 6 8 10
Editor
Python
Hints
__next__ returns the next value or raises StopIteration.
An iterator is used up once it finishes.
Solution explanation
This is what a for loop does under the hood: call iter(), then next() until StopIteration.
Show solution
class EvenNumbers:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current > self.limit:
raise StopIteration
value = self.current
self.current += 2
return value
limit = int(input())
print(*EvenNumbers(limit))
print(*EvenNumbers(limit))