Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsMiddleVery commonTheory

How does a function containing `yield` behave differently from a normal function?

Answer

Any function whose body contains at least one `yield` statement becomes a generator function: calling it does not run the body at all, it immediately returns a generator object that implements the iterator protocol for you automatically. Each call to `next()` on that generator runs the function body until the next `yield` expression, pauses execution there, and returns the yielded value; the function's entire local state — variables, the instruction pointer, even open loops — is preserved between calls, and execution resumes exactly where it left off on the following `next()`.

Strong answer includes

  • presence of yield makes it a generator function
  • calling it returns a generator object without running the body
  • execution pauses at yield and resumes with full local state preserved

Practical example

Generator pauses and resumes around yield
Python
editable · browser sandbox
Result
Run the code to see the result.

Calling countdown creates the generator without running its body. Each consumption resumes execution until the next yield and preserves n between resumptions.

Expected result: created, started, 3, 2, then [1].

#generators#yield

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsReal Python tutorialsReal Python · Coverage and explanation-style cross-check for intermediate and advanced Python topics