Home >Backend Development >Python Tutorial >How Can I Efficiently Flatten a List of Lists in Python?

How Can I Efficiently Flatten a List of Lists in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 18:14:10461browse

How Can I Efficiently Flatten a List of Lists in Python?

Flattening a List of Lists

You have a list of lists and desire to transform it into a single, flat list. For instance, you might have:

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

And aim to obtain:

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

Solution

A nested list comprehension offers an elegant solution to flattening a list of lists:

flat_list = [x for xs in xss for x in xs]

This code iterates over each sublist in xss and its elements, accumulating the results in flat_list.

Alternatively, you can flatten using a list comprehension with a join, or use the sum() function:

flat_list = [j for i in xss for j in i]
flat_list = sum(xss, [])  # or sum(xss)

Performance Comparison

While these methods provide equivalent results, their performance varies. Benchmarks show the nested list comprehension to be significantly faster than the other approaches, particularly for large input lists.

This superior performance stems from the fact that the list comprehension generates a single list once, copying each item only once. In contrast, the join-based method creates numerous intermediate lists, while the sum() approach involves a more complex operation.

Recursive Approach

If your list of lists has an arbitrary nesting depth, you may need a recursive approach for complete flattening. Consider the following function:

def flatten_completely(xss):
    return [x for elem in xss for x in flatten_completely(elem) if not isinstance(x, list)] if isinstance(xss, list) else [xss]

The above is the detailed content of How Can I Efficiently Flatten a List of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn