Flatten a Nested List
Source: Dev.to
Hey everyone! ๐
I know Iโve been a bit quiet lately. I actually came down with a pretty bad flu last week, which completely knocked me out. ๐ค Thatโs why I missed posting about the coding challenges. Iโm finally feeling a bit better and ready to get back into the swing of things!
Problem Statement
The goal is to write a function that takes a list which might contain other lists (nested to any depth) and converts it into a single, oneโdimensional list.
Examples
flatten([[1, 2], [3, 4], [5, 6]]) # โ [1, 2, 3, 4, 5, 6]
flatten([1, [2, 3], [[4, 5], 6]]) # โ [1, 2, 3, 4, 5, 6]
Solution
Here is the Python implementation using recursion. Recursion is perfect here because we donโt know how deep the nesting goes!
def flatten(nested_list):
"""
Flattens a nested list into a single-level list.
"""
result = []
for item in nested_list:
if isinstance(item, list):
flattened_sublist = flatten(item) # Recursively flatten the sublist
result.extend(flattened_sublist)
else:
result.append(item)
return result
# Test cases
print(flatten([[1, 2], [3, 4], [5, 6]]))
# Output: [1, 2, 3, 4, 5, 6]
print(flatten([1, [2, 3], [[4, 5], 6]]))
# Output: [1, 2, 3, 4, 5, 6]
Explanation
- Function definition โ
def flatten(nested_list):defines a function that accepts the potentially nested list. - Initialize result โ
result = []creates an empty list to collect flattened elements. - Iterate โ
for item in nested_list:loops over each element. - Check for sublist โ
if isinstance(item, list):determines whether the current element is itself a list. - Recursive call โ
flattened_sublist = flatten(item)flattens the sublist. - Extend result โ
result.extend(flattened_sublist)adds the flattened elements to the main result list. - Handle nonโlist items โ
else: result.append(item)directly appends atomic elements. - Return โ
return resultyields the fully flattened list.
The beauty of this function is its flexibility. Thanks to recursion, it can handle a list nested 2 levels deep or 200 levels deep with the exact same logic!
Thanks for sticking with me while I recovered! Iโll be catching up on more challenges soon. Happy coding! ๐ป