typestar

yield from in Python

Delegating iteration to a sub-generator, for recursion.

def walk(node):
    yield node["name"]
    for child in node.get("children", []):
        yield from walk(child)


tree = {
    "name": "root",
    "children": [
        {"name": "src", "children": [{"name": "app.py"}]},
        {"name": "README.md"},
    ],
}

names = list(walk(tree))

How it works

  1. yield from walk(child) re-emits a child's values.
  2. It flattens a recursive tree walk cleanly.
  3. list collects every name in visit order.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
242
Tokens
97
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 2 of 5 in Generators & itertools, step 11 of 53 in Pythonic Python.

← Previous Next →