5 Best Ways to Flatten a Python List

πŸ’‘ Problem Formulation: When working with lists in Python, developers often encounter nested lists (lists within lists) and require a flat version for further processing. Consider having [[1, 2, [3]], 4] and the goal is to transform it into [1, 2, 3, 4]. Flattening becomes essential for operations that cannot handle such nesting effectively. This article explores diverse approaches to flatten nested lists in Python.

Method 1: Using a Recursive Function

A recursive function is excellent for flattening lists of unknown depth. It works by checking if an element is a list and, if so, recurses down into that list to flatten it further. This is a robust way to handle lists with multiple levels of nesting.

Here’s an example:

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

nested_list = [[1, 2, [3]], 4]
flat_list = flatten_list(nested_list)
print(flat_list)

Output:

[1, 2, 3, 4]

This code snippet defines a function flatten_list that iteratively checks each element of the input list. If the element is also a list, it calls itself recursively to flatten it, otherwise, the element is added to the result list.

Method 2: Using itertools.chain

The itertools.chain function from Python’s itertools library is used to flatten a list that has only one level of nesting. It’s not suitable for deeply nested lists, but it is efficient for shallow structures.

Here’s an example:

import itertools

nested_list = [[1, 2], [3, 4]]
flat_list = list(itertools.chain(*nested_list))
print(flat_list)

Output:

[1, 2, 3, 4]

This snippet flattens a one-level nested list by unpacking each sublist into the chain function, which then iteratively returns each element, resulting in a flat list when converted.

Method 3: Using a Comprehension

List comprehensions offer a Pythonic way to flatten a list that is only one level deep. This method is straightforward, easy to read, and doesn’t require additional library imports.

Here’s an example:

nested_list = [[1, 2], [3, 4]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)

Output:

[1, 2, 3, 4]

In this code snippet, we use a nested list comprehension to iterate over each sublist item and collect the items into a new list, achieving a flattened list.

Method 4: Using functools.reduce and operator.concat

The functools.reduce function can be used to apply the operator.concat method repeatedly on a list, effectively flattening it. This method is well-suited for lists with a single level of nesting.

Here’s an example:

import functools
import operator

nested_list = [[1, 2], [3, 4]]
flat_list = functools.reduce(operator.concat, nested_list)
print(flat_list)

Output:

[1, 2, 3, 4]

The functools.reduce function applies operator.concat to the first two elements of the list, then to the result and the next element, and so on until the list is entirely flattened.

Bonus One-Liner Method 5: Using sum

The built-in sum function combined with a generator expression can flatten a list with a single level of nesting. Be cautious as this method is not performant with larger lists due to the way sum is used.

Here’s an example:

nested_list = [[1, 2], [3, 4]]
flat_list = sum(nested_list, [])
print(flat_list)

Output:

[1, 2, 3, 4]

By using sum with an initial empty list, we concatenate sublists of the original nested list into a single list which results in a flattened list.

Summary/Discussion

  • Method 1: Recursive Function. Handles deep nesting. May hit recursion limit with very deep lists.
  • Method 2: itertools.chain. Efficient for shallow lists. Ineffective for deep nesting.
  • Method 3: List Comprehension. Pythonic and readable. Only for single-level nesting.
  • Method 4: functools.reduce and operator.concat. Functional approach. Only for single-level nesting.
  • Method 5: Using sum. Simple one-liner. Poor performance with large lists.