Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

How does `generator.send(value)` differ from `next(generator)`, and what does it enable?

Answer

`next(gen)` resumes a generator and implicitly sends in `None` at the paused `yield` expression. `gen.send(value)` resumes the generator and makes that `value` become the result of the paused `yield` expression itself, turning the generator into a two-way communication channel rather than a one-way value producer. This is the mechanism that made coroutine-style generators possible before native `async`/`await`, though modern code almost always prefers `async`/`await` for that use case and reserves plain generators for simple value production.

Strong answer includes

  • next() implicitly sends None into the paused yield
  • send(value) makes value become the yield expression's result
  • historically enabled coroutine-style generators, now superseded by async/await

Practical example

Python example
def echo():
    while True:
        received = yield
        print("got", received)

requires priming with

Python example
next(gen)

once, after which

Python example
gen.send("hi")

prints `got hi` and pauses again at the same

Python example
yield

.

#generators#coroutines

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsPEP 380 — Syntax for Delegating to a SubgeneratorPython Software Foundation · yield from delegation semantics