Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresJuniorVery commonPractical

Flatten a list of lists by one level using idiomatic Python.

Answer

A nested list comprehension is concise when the input is explicitly one level deep: iterate over each inner collection and then over each item inside it. The comprehension preserves left-to-right order and creates one new list. It should not be presented as a recursive flattening solution because deeper arbitrary nesting needs different logic.

Strong answer includes

  • uses a nested comprehension correctly
  • preserves input order
  • distinguishes one-level flattening from recursive flattening

Practical example

Nested comprehension
Python
editable · browser sandbox
Result
Run the code to see the result.

The first `for` chooses each inner list; the second yields each item from that list into the output.

Expected result: [1, 2, 3, 4]

#lists#comprehensions#algorithms

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics