Iterators in Python — a practical guide to Python iterators with clear examples you can reuse in real projects.
Python Tutorial Series (52/95). Prefer one article? Read the complete Python tutorial.
Short description
Iterators produce values lazily with `next()` until `StopIteration`.
Custom iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
print(list(Countdown(3)))