5 Best Ways to Convert a Nested List into a Flat List in Python

πŸ’‘ Problem Formulation: In Python, converting a nested list (a list that contains other lists) into a flat list (one with no sublists; all elements are on the same level) is a common requirement. For example, if you have an input like [[1,2], [3,4], [5,[6,7]]], the desired output would be a flat list: [1, 2, 3, 4, 5, 6, 7]. This article demonstrates several techniques to achieve such a transformation effectively.

Method 1: Using a Recursive Function

By defining a custom recursive function, you can flatten a complex, deeply nested list. This method involves checking each element of the list and, if it’s itself a list, the function is called recursively. Otherwise, the element is added to the output list.

β™₯️ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month

Here’s an example:

def flatten_list(nested_list):
    flat_list = []
    for element in nested_list:
        if isinstance(element, list):
            flat_list.extend(flatten_list(element))
        else:
            flat_list.append(element)
    return flat_list

# Test the function
print(flatten_list([[1,2], [3,4], [5,[6,7]]]))

Output:

[1, 2, 3, 4, 5, 6, 7]

The recursive function flatten_list() traverses all the items in the given list. If the item is a list itself, it calls flatten_list() again, otherwise, it appends the element to flat_list. This continues until all levels of the nested list are processed.

Method 2: Using Itertools.chain

The itertools.chain function can be used to concatenate different iterable objects. When dealing with lists of lists, it flattens them into a single iterator that can then be converted to a list.

Here’s an example:

from itertools import chain

nested_list = [[1,2], [3,4], [5,[6,7]]]
flat_list = list(chain.from_iterable(nested_list))

# Test the result
print(flat_list)

Output:

[1, 2, 3, 4, 5, [6, 7]]

Notice that itertools.chain.from_iterable() will only work for one level of nesting. In the example, the sub-nested list [6, 7] is not flattened. This method is efficient but won’t handle deeply nested lists correctly.

Method 3: Using List Comprehensions

List comprehension in Python provides a concise way to create lists. It can be used to flatten a nested list by iterating through each element and extending the flat list if the element is itself a list.

Here’s an example:

nested_list = [[1,2], [3,4], [5,[6,7]]]

def flatten(nested_list):
    return [element for sublist in nested_list for element in (flatten(sublist) if isinstance(sublist, list) else [sublist])]

# Test the function
print(flatten(nested_list))

Output:

[1, 2, 3, 4, 5, 6, 7]

This snippet uses a nested list comprehension that includes a condition to handle sublists. If the item is a list, the function flatten() is called, otherwise the item is added directly to the new list. This method handles deeply nested lists as well.

Method 4: Using a Stack

A stack can be used to iterate through the nested list and flatten it by popping elements from the stack one at a time. When a sublist is encountered, its elements are added back to the stack for further processing.

Here’s an example:

def flatten(nested_list):
    flat_list = []
    stack = list(reversed(nested_list))
    
    while stack:
        element = stack.pop()
        if isinstance(element, list):
            stack.extend(reversed(element))
        else:
            flat_list.append(element)
    return flat_list

# Test the function
print(flatten([[1,2], [3,4], [5,[6,7]]]))

Output:

[1, 2, 3, 4, 5, 6, 7]

The stack implementation ensures all elements are processed and flattens even deeply nested lists effectively. Elements are reversed and appended back to the stack to maintain their original order when encountered as a sublist.

Bonus One-Liner Method 5: Using a Single List Comprehension

With certain constraints on list structure (e.g., two levels of nesting), you can use a single list comprehension as a one-liner method to flatten the list.

Here’s an example:

flat_list = [item for sublist in [[1,2], [3,4], [5,6,7]] for item in sublist]

# Test the result
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7]

This method is a compact and readable way to flatten a singly nested list, but it’s not suitable for handling more complex or deeper nested lists as it doesn’t incorporate any recursion or iterative checks.

Summary/Discussion

  • Method 1: Recursive Function. Handles any level of nesting. Can be slow for large lists due to the overhead of the recursive calls.
  • Method 2: Itertools.chain. Efficient for a single level of nesting. Not suitable for deeply nested lists.
  • Method 3: List Comprehensions. Concise and handles multiple levels of nesting. Could get complex and less readable for deeply nested lists.
  • Method 4: Stack. Effective for all nesting levels. More imperative and might be less pythonic than list comprehensions or recursive methods.
  • Bonus Method 5: Single List Comprehension. Short and sweet for two levels of nesting. Not suitable for lists with more than one level of nested sublists.