iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Iterators

An iterator produces values one at a time. Everything you can for-loop over is either an iterator or knows how to give you one.

The protocol

MethodWhat it does
__iter__()Returns an iterator (usually self).
__next__()Returns the next value, or raises StopIteration.

Building one by hand

PYTHON
class Count:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        self.i = 0
        return self
    def __next__(self):
        if self.i >= self.n:
            raise StopIteration
        self.i += 1
        return self.i

for x in Count(3):
    print(x)   # 1, 2, 3

Generators — the easy way

A function with yield automatically becomes an iterator:

PYTHON
def count(n):
    for i in range(1, n + 1):
        yield i

for x in count(3):
    print(x)

Why generators are powerful

  • Lazy — values are computed on demand, not all at once.
  • Memory-friendly — never materialise a giant list you'd only loop over.
  • Composable — chain together with itertools.
Tip: Generator expressions look like list comprehensions with parens: sum(n * n for n in range(10_000)). No intermediate list — just streams numbers through sum.

Example

Example
class Count:
    def __init__(self, n): self.n = n
    def __iter__(self): self.i = 0; return self
    def __next__(self):
        if self.i >= self.n: raise StopIteration
        self.i += 1
        return self.i

for x in Count(3):
    print(x)
Try it Yourself »

Exercise

Turn a function into a generator with this keyword.

def count(n): for i in range(n): i

Test yourself

Q1. An iterator must implement…
Q2. A function becomes a generator when it uses…
Q3. Generators are…

Discussion

Loading…