Explore Library
Code Quiz

Exhausted Generator in a Pipeline

Spot the subtle bug when a single-use generator is iterated twice in a memory-efficient pipeline.

Codepython
def read_numbers(path):
    with open(path) as f:
        for line in f:
            yield int(line.strip())

def average(path):
    nums = read_numbers(path)
    total = sum(nums)
    count = sum(1 for _ in nums)
    return total / count

print(average('data.txt'))

This pipeline is designed to stream a huge file without loading it into memory, but it crashes or misbehaves. What is the bug?