micropython iterator code example
Example 1: python defining the iterator protocol
class RangeTen:
def __init__(self, *args): pass
def __iter__(self):
'''Initialize the iterator.'''
self.count = -1
return self
def __next__(self):
'''Called for each iteration. Raise StopIteration when done.'''
if self.count < 9:
self.count += 1
return self.count
raise StopIteration
for x in RangeTen():
print(x)
Example 2: iterator in python
my_list = [4, 7, 0, 3]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter)