yield

yield turns a function into a generator: it hands out one value, pauses, and continues when asked again.

Syntax

def path():
yield (0, 0)
yield (1, 0)
  • for x in path(): asks for each yield. list(path()) collects them all.

Example

def count():
    yield 1
    yield 2

print(list(count()))

Output:

[1, 2]

Common mistakes

  • return ends the function at once, so a second return never runs. Use yield to send more than one value.

Practise it