Skip to content Skip to sidebar Skip to footer

How To Recursively Add Items To A List?

Currently, I'm working on a problem. I am given a list, whose elements may contain other lists, lists of lists, or integers. For example, I may receive: [[[[], 1, []], 2, [[], 3, [

Solution 1:

Pass the list to append to as a parameter.

def fun(a, result):
    if type(a) == int:
        print("Found a digit: ", a)
        result.append(a)
    else:
        for i in a:
            fun(i, result)
old_list = [[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]]
new_list = []
fun(old_list, new_list)
print(new_list)

If you need the original function signature, you can split this into two functions.

def fun(a):
    result = []
    fun_recursive(a, result)
    return result

fun_recursive() would be defined as above.

Solution 2:

you can try:

def fun(a):
    if isinstance(a, int):
        yield a
    else:
        for e in a:
            yield from fun(e)

print(list(fun([[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]])))

output:

[1, 2, 3, 4, 5, 6, 7, 9]

Post a Comment for "How To Recursively Add Items To A List?"