Search code examples
pythonnested-lists

Extracting the deepest list or lists in a nested list


I am new to python and struggling with nested lists. In particular, I have been given a nested list from which I need to extract the deepest list (or lists, if there are more than one list at the deepest depth). I've coded the below, but it's only returning one of the two deepest lists (the other one would be [4421, 4422]). Could someone explain what I'm doing wrong? There's a related question from before but, similarly, the suggested solutions could only provide the first of two deepest lists. Thank you.

def deepest_list(l):
    deeps = []
    for item in l:
        if isinstance(item, list):
            return deepest_list(item)
        else:
            deeps.append(item)
        continue
    return deeps

deepest_list([1, [21, [[2211, 2212], 222]], [[311], 32, [331]], [41, 42, 43, [441, [4421, 4422]]]])

Solution

  • Try this:

    def deepest_lists(lst):
        lsts = [item for item in lst if isinstance(item, list)]
        if len(lsts) == 0:
            return lsts
        if all(isinstance(item, int) for lst in lsts for item in lst):
            return lsts
        return deepest_lists([item for lst in lsts for item in lst])
    

    Example:

    >>> lst = [1, [21, [[2211, 2212], 222]], [[311], 32, [331]], [41, 42, 43, [441, [4421, 4422]]]]
    >>> deepest_lists(lst)
    [[2211, 2212], [4421, 4422]]