Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

I'm working with a recursive function to add all 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 a 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 is giving an incorrect answer, i.e., 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]))

It gives me this 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 do one work-around work and the other fail? I want to "declare variables" but this is not a python thing. Should I look in to "global variables"?

1 Answer

0 votes
by (36.8k points)
edited by

If K is outside the 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, to see this question click here

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!

Do check out Python Data Science Course which helps you understand from scratch  

Browse Categories

...