๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 14 of 40
Lesson 14 of 40 Core Python Intermediate โฑ 35 min

Iterators, Generators & yield

Build memory-efficient data pipelines with __iter__/__next__, generator functions, yield from, generator expressions, and send().

Part 1: What You Will Learn

  • Implement the iterator protocol with __iter__() and __next__().
  • Write generator functions with yield.
  • Delegate with yield from.
  • Build lazy pipelines that process data without loading everything into memory.

Part 2: Key Concepts

An iterator produces one item at a time and raises StopIteration when finished. A generator is a simpler way to create an iterator: Python automatically stores the function state each time yield pauses execution.

Part 3: Topic-Specific Code Example

class Countdown:
    def __init__(self, start: int) -> None:
        self.current = start

    def __iter__(self):
        return self

    def __next__(self) -> int:
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value


def order_batches():
    yield from [120.50, 80.00, 210.75]
    yield from [45.90, 330.00]


def large_orders(orders, minimum: float):
    for amount in orders:
        if amount >= minimum:
            yield amount

print("Countdown:", list(Countdown(5)))

pipeline = large_orders(order_batches(), minimum=100)
for amount in pipeline:
    print(f"Large order: RM{amount:.2f}")

squares = (number * number for number in range(1, 6))
print("Generator expression:", list(squares))

Part 4: How the Example Works

Countdown shows the iterator protocol directly. The two generator functions are shorter because yield handles iteration state automatically. yield from forwards every item from another iterable, and the generator expression calculates each square only when requested.

Part 5: Hands-On Practice

Mini project โ€” Log Stream Filter. Write a generator that receives log lines one by one and yields only lines containing ERROR. Add another generator that transforms the matching lines into dictionaries with time, level, and message fields.

Part 6: Next Steps

Run and modify the examples in Visual Studio 2026, then continue to Lesson 15. Return to Python Tutorial Home to review the complete curriculum.

๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’