typestar

Flatten nested lists in Python

Recursion handles arbitrarily nested data where plain loops get clumsy.

def flatten(nested):
    flat = []
    for item in nested:
        if isinstance(item, list):
            flat.extend(flatten(item))
        else:
            flat.append(item)
    return flat

How it works

  1. Walks each item of a possibly nested list.
  2. Lists recurse via isinstance; everything else is appended.
  3. Returns one flat list of all the leaf values.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
140
Tokens
42
Three-star pace
95 tpm

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

Type this snippet

Step 6 of 10 in Collections, step 28 of 72 in Language basics.

← Previous Next →