Flatten a Nested List

Published: (December 8, 2025 at 05:55 AM EST)
2 min read
Source: Dev.to

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 result yields 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! ๐Ÿ’ป

Back to Blog

Related posts

Read more ยป

Monkey Market

Part 1 Another math gauntlet I get to program a bunch of math operations. Some will be part of several conditionals. I've done it before. I'm confident I can d...