Iterators
An iterable (a list, string, dict...) can be looped over. iter() gives an iterator and next() returns the next item until StopIteration is raised. A for loop does this for you. You can build your own iterator with a class that has __iter__ and __next__.
Example
it = iter(["a", "b"])
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("finished")
class Count:
def __init__(self, stop):
self.n, self.stop = 0, stop
def __iter__(self):
return self
def __next__(self):
if self.n >= self.stop:
raise StopIteration
self.n += 1
return self.n
print(list(Count(3)))Result
a b finished [1, 2, 3]
Exercise
Get the next item of an iterator.
print((it))
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.