1

I'm working with a recursive function to add all the the integers in nested lists.

def myFunction(L):
    K=[]
    for eachItem in L:
        if isinstance(eachItem, list):
            myFunction(eachItem) #to deal with nested Lists.
        else:
            K.append(eachItem) 
    return sum(K) #add em up!
    


print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))

Result: 9

This fails because K=[] is inside of the recursive function, so only the totally unnested values are summed.

I can fix it by doing this:

K=[] #moved it up here
def myFunction(L):
   
    for eachItem in L:
        if isinstance(eachItem, list):
            myFunction(eachItem) #to deal with nested Lists.
        else:
            K.append(eachItem) 
    return sum(K) #add em up!
    


print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))

Now I get the result that I want, 12.

But when I try to do the same thing with an integer:

def myFunction(L):
    K=0
    for eachItem in L:
        if isinstance(eachItem, list):
            myFunction(eachItem) #to deal with nested Lists.
        else:
            K +=eachItem
    return K #add em up!
    


print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))

Having K inside the loop gives me the incorrect answer 9, and moving it out:

K=0
def myFunction(L):
    
    for eachItem in L:
        if isinstance(eachItem, list):
            myFunction(eachItem) #to deal with nested Lists.
        else:
            K +=eachItem
    return K #add em up!
    


print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))

Gives me an error "UnboundLocalError: local variable 'K' referenced before assignment" because it can't do "K +=eachItem" so, K isn't a part of the variable in the function?

Why does one work-around work and the other fail? I want to "declare variables" but this isn't a python thing. Should I look in to "global variables" ?

futurebird
  • 73
  • 7
  • Does this answer your question? [How to recursively add items to a list?](https://stackoverflow.com/questions/58174992/how-to-recursively-add-items-to-a-list) – wwii Jul 04 '20 at 20:56
  • no, I'm not having trouble with that. This is a problem with the scope of variables and understanding why lists are doing something different. – futurebird Jul 04 '20 at 21:16
  • .. adding the list as a function argument/parameter - like in the accepted answer - solves your problem. – wwii Jul 04 '20 at 21:20

3 Answers3

1

If K is outside your function, you have to declare K as a global variable for it to be recognized. As for why it works with a list and not with an integer, see this question In Python, why is list[] automatically global?.

K = 0
def myFunction(L):
    global K
    for eachItem in L:
        if isinstance(eachItem, list):
            myFunction(eachItem)  # to deal with nested Lists.
        else:
            K += eachItem
    return K  # add em up!
zmike
  • 1,090
  • 10
  • 24
1

You could instead define K as an argument to myFunction as such:

def myFunction(L,K=0):
  for eachItem in L:
    if isinstance(eachItem, list):
      K = myFunction(eachItem, K)
    else:
      K += eachItem

  return K

print(myFunction([[1,2,[2],2],[[[3]],-7],4,5])) # 12
heittpr
  • 591
  • 4
  • 9
1

You really don't need K at all (and certainly can avoid the global). If your function returns a number you can include the recursion in the sum.

def myFunction(l):
    return sum(n if not isinstance(n, list) else myFunction(n) for n in l)

print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))
# 12

Alternatively, you can recurse all the way down to the numbers and just sum the recursion:

def myFunction(l):
    if isinstance(l, list):
        return sum(map(myFunction, l))
    else:
        return l

print(myFunction([[1,2,[2],2],[[[3]],-7],4,5]))
# also 12
Mark
  • 90,562
  • 7
  • 108
  • 148
  • This is neat, but I need to do other things with each list entry that I stripped out to make the problem more simple for posting. – futurebird Jul 04 '20 at 21:29