Yield

3 snippets across 2 stacks — Python, JavaScript

Also written as yield from

PYPython

Generators with yield

PY · Functions
syntax
def gen():
    yield value
example
def countdown(n: int):
    while n > 0:
        yield n
        n -= 1

for tick in countdown(3):
    print(tick)

# Generators are lazy — values produced one at a time
nums = countdown(1_000_000)
print(next(nums))
output
3
2
1
1000000

Note Generators produce values lazily, consuming almost no memory regardless of size. They are single-use: once exhausted, they cannot be restarted.

yield from (Delegation)

PY · Comprehensions & Generators
syntax
yield from iterable
example
def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

data = [1, [2, [3, 4]], [5, 6]]
print(list(flatten(data)))
output
[1, 2, 3, 4, 5, 6]

Note yield from delegates to a sub-generator and passes values through. It handles send() and throw() transparently, unlike a manual for-loop with yield.

JSJavaScript

Generator Functions

JS · Functions
syntax
function* name() { yield value; }
example
function* idGenerator(start = 1) {
  let id = start;
  while (true) {
    yield id++;
  }
}
const ids = idGenerator(100);
console.log(ids.next().value); // 100
console.log(ids.next().value); // 101
console.log(ids.next().value); // 102

Note Generators are lazy -- they produce values on demand. Execution pauses at each yield and resumes when next() is called.