Friday, June 12, 2020

I have been using this Python function to flatten an arbitrarily deep nested list

#!/usr/bin/env python


def flatten(arg: list, sort_results=False) -> list:
    """
    This function takes an object graph (really, just a list of lists/tuples of
    lists/tuples etc) and flattens it into a one-dimensional list.
    """

    def helper(result, arg):
        if isinstance(arg, list):
            for x in arg:
                helper(result, x)
        elif isinstance(arg, tuple):
            for x in arg:
                helper(result, x)
        elif isinstance(arg, set):
            for x in sorted(arg):
                helper(result, x)
        else:
            result.append(arg)
        return result

    r = helper(list(), arg)
    return sorted(r) if sort_results else r


def main():
    inp = [100, [200, 201, 202], [310, [311, 312, 313, [314, 315]]]]
    out = flatten(inp)
    print(f"{inp=}")
    print(f"{out=}")


if __name__ == "__main__":
    main()


When run at the command line, you see:

$ python ./flatten.py
inp=[100, [200, 201, 202], [310, [311, 312, 313, [314, 315]]]]
out=[100, 200, 201, 202, 310, 311, 312, 313, 314, 315]


Not sure of its efficiency, though.