Search code examples
pythonfunctionreturnreturn-value

Python recursive function returns none type even after using the return to the function?


I am working on this code segment:

result=[]
def function(i,x,Tree,result):
    if isinstance(Tree,ExNode):     
        return 0    
    a=Tree.tempatt
    if x[a]<Tree.tempval:            
        return result.append(Tree.val), function(i,x,Tree.left,result)
    else:                   
        return result.append(Tree.val), function(i,x,Tree.right,result)

Here, tempatt, tempval, val are the components of the Tree class.

This function works as desired but return None. However, in the variable explorer I can see the result variable with the desired values forming a list.


Solution

  • Write it like this

    result=[]
    def function(i,x,Tree,result):
        if isinstance(Tree,ExNode):     
            return 0    
        a=Tree.tempatt
        if x[a]<Tree.tempval:  
            result.append(Tree.val), function(i,x,Tree.left,result)  
            return result
        else:
            result.append(Tree.val), function(i,x,Tree.right,result)          
            return result
    

    In your case you weren't returning a list , but a function which returns none