Search code examples
pythonlistnested

Addition to nested list


I wanted to add element with the next value to the most nested list, i. e.

For list

list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]

The program should return

list_out = [2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

In case with e. x. two equal nests, I wanted to get:

list_in = [2, [4], [3]]

list_out = [2, [4, 5], [3, 4]]

How to do it?


Solution

  • A recursive solution:

    list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]
    
    
    def get_depths(lst, depths, current_depth=0):
        out = [
            get_depths(v, depths, current_depth + 1) if isinstance(v, list) else v
            for v in lst
        ]
        depths.setdefault(current_depth, []).append(out)
        return out
    
    
    depths = {}
    list_out = get_depths(list_in, depths)
    for lst in depths[max(depths)]:
        lst.append(lst[-1] + 1)
    
    print(list_out)
    

    Prints:

    [2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]
    

    For list_in = [2, [4], [3]] it prints:

    [2, [4, 5], [3, 4]]