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!
Today, we're tackling a classic problem: Flattening a Nested List.
The Problem
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]])should return[1, 2, 3, 4, 5, 6] -
flatten([1, [2, 3], [[4, 5], 6]])should return[1, 2, 3, 4, 5, 6]
The 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]
Code Breakdown
Let's walk through the code line by line to understand exactly what's happening.
-
def flatten(nested_list):- Defines a function called
flattenthat takesnested_listas input.
- Defines a function called
-
result = []- Initializes an empty list called
result. This will store our final flattened elements.
- Initializes an empty list called
-
for item in nested_list:- Begins iterating through each element in the input
nested_list.
- Begins iterating through each element in the input
-
if isinstance(item, list):- Checks if the current
itemis a list usingisinstance(). This is the crucial step that detects nested lists.
- Checks if the current
-
flattened_sublist = flatten(item)- If the item is a list, we recursively call
flatten()on it. This handles the "nesting" by treating that sublist as its own problem to solve.
- If the item is a list, we recursively call
-
result.extend(flattened_sublist)- Since
flatten()returns a list, we use.extend()to add all those individual elements to our mainresultlist. If we used.append(), we'd just end up with another list inside our result!
- Since
-
else:-
result.append(item) - If the item is not a list (it's just a number, string, etc.), we directly add it to
result.
-
-
return result- Finally, returns the fully processed, flat 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! π»
Top comments (0)