[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
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
Comments
Post a Comment