Flatten Nested Lists
Convert a nested list structure into a flat list.
Code
Python
def flatten(nested):
result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
data = [1, [2, 3], [4, [5, 6]]]
print(flatten(data)) # [1, 2, 3, 4, 5, 6]Line-by-line explanation
- 1.Define a recursive flatten function.
- 2.Iterate over each item in the list.
- 3.If the item is a list, recursively flatten it and extend the result.
- 4.Otherwise append the item directly.
- 5.Return the flattened list.
Expected output
[1, 2, 3, 4, 5, 6]