Flatten Nested Lists

Python data engineering interview problem. Difficulty: beginner. Pattern: Recursion. About 10 minutes. Free to practice.

Flatten arbitrarily nested lists without splitting strings. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Data often arrives as lists inside lists, for example when an API returns groups of items. Before you can use it, you need one simple flat list. Write a function flatten(nested) that takes a list which may contain numbers, strings and more lists (which can contain even more lists, to any depth). Return one flat list with all the values, in the same left-to-right order as they appear. Strings must stay whole. The string 'ab' is one value, so it must not be split into 'a' and 'b'. The editor already gives you an empty function and two print lines at the bottom. Keep those print lines. They run your function when you click Run.

Requirements

  • Return a single list with no lists inside it.
  • Keep the values in the same left-to-right order as in the input.
  • Keep every value as it is. A number stays a number, and a string stays one whole string.
  • Work for any depth of nesting, not just 2 levels.

Constraints

  • nested is a list. Its items can be ints, strings or other lists.
  • Do not split strings into characters, even though a string can be looped over in Python.
  • You do not know in advance how deep the nesting goes, so a fixed number of loops will not be enough.

Examples

Input: flatten([1, [2, [3, 4]], 5]) Output: [1, 2, 3, 4, 5] Nested lists unwrap left-to-right.

Topics: lakebench, python, flatten, lists.

More Python interview questions · All interview problems · Learn data engineering

beginner

Flatten Nested Lists

Interview-style drill: Flatten arbitrarily nested lists without splitting strings.

Implement `flatten(nested)` that flattens nested lists to any depth into one list of leaf values. Strings must stay whole (do not iterate characters). Example: `[1, [2, [3, 4]], 5]` → `[1, 2, 3, 4, 5]`. Keep the harness prints.