Advertisement
Intermediate Python, Comprehensions & Generators

How do you send a value INTO a generator using the .send() method, and how does this differ from just calling next()?

Short answer

generator.send(value) resumes the generator's execution and makes 'value' become the RESULT of the 'yield' expression that's currently paused — unlike next() (equivalent to send(None)), send() lets you communicate data back INTO the generator's ongoing execution, enabling…

Save Python mock interview
Advertisement
AModel answer
generator.send(value) resumes the generator's execution and makes 'value' become the RESULT of the 'yield' expression that's currently paused — unlike next() (equivalent to send(None)), send() lets you communicate data back INTO the generator's ongoing execution, enabling coroutine-like two-way communication.
def echo():
    while True:
        received = yield
        print(f"Received: {received}")

gen = echo()
next(gen)          # prime the generator to the first yield
gen.send("hello")   # prints "Received: hello"
Real-world example
Building a simple coroutine-style consumer that processes values pushed to it one at a time, a pattern predating async/await.
Likely follow-ups
  • Why must you call next() (or send(None)) once to 'prime' a generator before you can send() a real value into it?
Related topics