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.
- Only lists are opened up. A tuple or a string is a single value: keep it as it is.
- Empty lists contribute nothing.
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 1
Walk the items: a list gets flattened (callflatten on it), anything else is appended.Hint 2
isinstance(x, list) is true only for lists, not tuples or strings.Hint 3
out.extend(flatten(x)) adds every item of the flattened sub-list.Learn the concepts
- Comprehensions · 5 min read. List, dict and set comprehensions, filtering versus choosing, nesting, and generator expressions.
More Python problems
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium