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()?
IntermediateAnswer
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.