Home >Backend Development >Python Tutorial >How Can We Efficiently Flatten Arbitrarily Nested Lists in Python?

How Can We Efficiently Flatten Arbitrarily Nested Lists in Python?

DDD
DDDOriginal
2024-12-28 16:04:11363browse

How Can We Efficiently Flatten Arbitrarily Nested Lists in Python?

Arbitrarily Nested List Flattening

Nested lists, with varying levels of depth, present a challenge in reducing them to a single dimension. While there are numerous solutions to flatten shallow lists, many struggle with irregularly nested lists, such as [[[1, 2, 3], [4, 5]], 6].

The Recursive Approach

One approach, as mentioned in the question, involves recursion:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

This algorithm iterates through the list, recursively flattening any nested lists and appending non-iterable elements to the result.

Generator Functions for Improved Readability and Performance

Generator functions provide an alternative approach that can enhance both the readability and efficiency of our flattening process.

Python 2

from collections import Iterable

def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, basestring):
            for item in flatten(x):
                yield item
        else:
            yield x

Python 3

from collections.abc import Iterable

def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

In Python 3, the yield from operator conveniently returns items from nested generators sequentially, while in Python 2, we explicitly iterate through the sub-generators.

The above is the detailed content of How Can We Efficiently Flatten Arbitrarily Nested 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