Skip to content

1. Flatten a Nested List

Difficulty: Easy · Topic: Core Python & data structures

A JSON payload arrived as lists nested inside lists, to any depth. Write flatten(items): return one flat list of every value that is not a list, in the order it appears.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

flatten([1, [2, 3], [4, [5, [6]]], 7])

Expected: [1, 2, 3, 4, 5, 6, 7]

Hints

Hint 1Walk the items: a list gets flattened (call flatten on it), anything else is appended.
Hint 2isinstance(x, list) is true only for lists, not tuples or strings.
Hint 3out.extend(flatten(x)) adds every item of the flattened sub-list.

Learn the concepts

More Python problems

All Python problems