0

I wrote a flatten function that turns a nested list into one list

def flatten(lst, new=[]):
    for i in lst:
        if type(i)==list:
            flatten(i)
        else:
            new+=[i]
    return new

I tried using the same logic to make a function that adds up all positive numbers found in the nested list.

def posSum(lst, Sum=0):
    for i in lst:
        if type(i)==list:
            posSum(i)
        else:
            if i > 0:
                Sum+=i
    return Sum

This returns 0. Why is it the "new" variable gets updated in flatten, but Sum doesn't get updated in posSum? I even put a print statement in my else clause to see if I could print out all the "i"s, which works. I tried putting a return for posSum instead of just calling it, but then it only calculates the sum for the first element since it breaks the loop. How can I get around this in one function, as opposed to me flattening the list, and then going through the new list?

DrJessop
  • 462
  • 6
  • 26

0 Answers0