Sobes.tech
Junior — Senior

Extend the flatten function to handle nested lists and tuples

livecode

Task condition

It is necessary to improve the flat function so that it recursively unpacks any nested lists and tuples, collecting all elements into a single one-dimensional list.

mylist = [[1, 2, [3, [4, (5, (5.5, [5.8]))]]], 6, 7, 8]

def flat(arr, result=None):
    if result is None:
        result = []
    for a in arr:
        if not isinstance(a, (list, tuple)):
            result.append(a)
        else:
            flat(a, result)
    return result

After modification, the function should correctly handle both lists and tuples, regardless of the depth of nesting, and return a flat list of all found elements.