Quick Answer
Convert multi-dimensional lists to flat lists.
Understanding the Issue
Flattening transforms nested lists into single dimension lists. Methods vary for regular vs. irregular nesting patterns.
The Problem
This code demonstrates the issue:
Python
Error
nested = [[1, 2], [3, [4, 5]], 6]
# Need [1, 2, 3, 4, 5, 6]
The Solution
Here's the corrected code:
Python
Fixed
# Solution 1: List comprehension (1-level)
flat = [item for sublist in nested for item in sublist]
# Solution 2: itertools.chain
from itertools import chain
flat = list(chain.from_iterable(nested))
# Solution 3: Recursive flattening
def flatten(xs):
for x in xs:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
flat = list(flatten(nested))
# Solution 4: pandas (for complex data)
import pandas as pd
flat = pd.json_normalize(nested).to_numpy().ravel()
Key Takeaways
Choose flattening method based on nesting depth and structure.