0

I have an unexpected result where values of self.path and self.path_temp are different and the only way they are different is that one is updated by a string and another by a list all passed through function trav as arguments. Are lists somehow persistent in memory in python? A correct or detailed explanation would be appreciated!

PS: The correct one is self.path which is updated with the string.


    def binaryTreePaths(self, root: TreeNode) -> List[str]:
                
        self.path = []
        temp = []
        self.path_temp = []

        
        def trav(root,path,temp):
            
            if root:
                
                path += str(root.val)
                temp.append(root.val)

                if root.right == None and root.left==None:
                    self.path.append('->'.join(path))
                    self.path_temp.append('->'.join(temp))
                
                    
                trav(root.left,path,temp)
                trav(root.right,path,temp)
        
        
        trav(root,'',temp)    
        print(self.path)
        print(self.path_temp)

2
  • What is ls??? Commented Aug 19, 2020 at 15:27
  • My bad, it was supposed to be temp. But it was a typo when i was changing variable names. It doesnt change the issue functional wise Commented Aug 19, 2020 at 15:29

1 Answer 1

2

The difference is that path is a primitive value (a string) and temp is not. When you do

path += str(root.val) 

You are actually creating a new string. Strings are immutable in Python. And so also, the caller of the function will not see any change in the path variable that it passed as argument.

It is a different story with temp. When you do

temp.append(root.val)

... you are mutating the temp list. This is the list that the caller passed as argument, and so the caller's list is mutated by this action. In all the recursive process there are several temp variable instances, but they all reference one and the same list. Every append affects all temp variable instances.

If you want temp to behave like path, then you must create a new list instead of mutating the existing one:

temp = temp + [root.val]

NB: don't shorten this to temp += [root.val], as then again you are muting the original list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.