Skip to main content

11. Iterators Basics

An iterator is an object that implements the iterator protocol with __iter__() and __next__().


Example of an Iterator

numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3

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

for n in CountDown(3):
print(n)

Wrap-Up

  • Iterators provide sequential access to elements.
  • Use iter() and next() to work with them directly.