[Python][Coding Pattern] Flatten Nested List

Flatten Nested List

Purpose

Convert a 2D list of integers (a list of lists) into a flat, single list while preserving the order of the integers.

Key Concepts

- This is about list comprehension with nested loops.

- The outer list holds inner lists (e.g., [[1, 2], [3, 4], [5]]), and each inner list holds integers.

- The task is to unpack all inner elements and return them in a single flat list.

Step-by-step Logic

1. Use a list comprehension

The entire transformation can be done in a single line.

It’s more efficient and concise than using traditional loops.

2. Start with a nested for-loop pattern

In a list comprehension, reverse the traditional for-loop order:

- First: for inner in nested — loop over each inner list.

- Second: for element in inner — loop over each element inside the current inner list.

3. Understand the loop structure

[element for inner in nested for element in inner]

reads as:

For each inner list in the nested list, extract each element from the inner list and collect it.

4. Why order is preserved

Because list comprehensions evaluate left to right, this goes row by row and item by item in order.

5. What gets returned

A new list that contains all integers from each inner list in their original order — fully flattened.

Key Python Techniques Used

- list comprehension with nested loops

- 2D list traversal

- Preserving order via list accumulation

# Problem:
# Given a nested list of integers (a list of lists), return a single flat list containing all the integers in order.

# Example:
# flatten([[1, 2], [3, 4], [5]]) -> [1, 2, 3, 4, 5]

# Constraints:
# - Use a list comprehension
# - Assume input is a list of lists of integers

def flatten(nested: list[list[int]]) -> list[int]:
    return [ element for inner in nested for element in inner]

if __name__ == '__main__':
    assert flatten([[1, 2], [3, 4], [5]]) == [1, 2, 3, 4, 5], 'test 1 failed'
    assert flatten([]) == [], 'test 2 failed'
    assert flatten([[42]]) == [42], 'test 3 failed'

Comments