1# user defined iterator used in something other than a for loop 2 3class MyStopIteration(StopIteration): 4 pass 5 6class myiter: 7 def __init__(self, i): 8 self.i = i 9 10 def __iter__(self): 11 return self 12 13 def __next__(self): 14 if self.i == 0: 15 raise StopIteration 16 elif self.i == 1: 17 raise StopIteration(1) 18 elif self.i == 2: 19 raise MyStopIteration 20 21print(list(myiter(0))) 22print(list(myiter(1))) 23print(list(myiter(2))) 24