Python Practice › Iterator & Generator Programs › Program 18
Send values into a generator
Write a generator that keeps a running average of values sent to it.
Output
10.0 15.0 30.0
Approach
value = yield resultreceives whatsend()passes.
Solution
def averager(): total, count, average = 0, 0, None while True: value = yield average total += value count += 1 average = total / count avg = averager()next(avg) # start the generatorprint(avg.send(10), avg.send(20), avg.send(60))Output
10.0 15.0 30.0
Line by line
Line 4
The generator pauses here, hands out the current average and waits for the next value.
Line 10
The first next() runs the code up to the first yield.
Learn the concept
New to this topic? Read the lesson, then come back.