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

How Can Python Generators Efficiently Flatten Arbitrarily Nested Lists?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 15:02:09691browse

How Can Python Generators Efficiently Flatten Arbitrarily Nested Lists?

Flattening Irregular Lists with Python Generators

The problem of flattening an arbitrarily nested list of lists is common, but existing solutions often fail for deeply nested structures. In particular, a list like [[[1, 2, 3], [4, 5]], 6] cannot be flattened using most solutions.

The following function, based on a solution from another question, can effectively flatten such lists:

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

However, while this function works, it can be improved in terms of readability and performance using generator functions.

Python 2 with Iterable ABC

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 with Iterable ABC and Yield From

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

These generator-based solutions provide a more concise and efficient way to flatten irregular lists. They work by iterating through each element in the list and recursively yielding elements for sublists. Any non-iterable elements (e.g., numbers or strings) are immediately yielded.

The above is the detailed content of How Can Python Generators Efficiently Flatten Arbitrarily Nested Lists?. 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