user545642
user545642

Reputation: 113

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, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]]

My goal is to parse the array, and append only the integers to a new list. Here is what I have done so far:

def fun(a):
    if a == []:
        return None
    elif type(a) == int:
        print("Found a digit: ", a)
        return a
    for i in a:
        fun(i)

Currently, this function recursively goes through the list and successfully finds each integer; now, I am having an issue with appending those integers to a new list, and returning that list at the very end. The output should be like this:

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

Any pointers?

Upvotes: 3

Views: 3822

Answers (2)

Barmar
Barmar

Reputation: 780909

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.

Upvotes: 6

kederrac
kederrac

Reputation: 17322

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]

Upvotes: 4

Related Questions