简体   繁体   中英

Change in variable made inside of a while loop is not reflected outside of the loop in Python 3

I have a variable (named root ) defined outside the while loop and am making changes to it inside the while loop but those changes are not being reflected outside the while loop. I have initialized my root variable as a TreeNode with value OLD_VALUE and then changes its value to NEW_VALUE inside the while loop. After printing the value of root outside the loop, it is still showing the original value ie OLD_VALUE . So, the pseudo-code is as follows (I can share the actual code if needed):

class TreeNode: #Defines nodes of a binary tree
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class Solution(object): #this is my main class where I have a problem
    def buildTree(self, pre, ino):
        ##some code
        root = TreeNode(OLD_VALUE) #This is the variable in question
        stack = [] #Basically I am sending the variable 'root' through this stack
        stack.append([item1, item2, item3, item4, root])
        while(stack):
            all_items = stack.pop()
            ##some code
            all_items[4] = TreeNode(NEW_VALUE) #Note, all_items[4] is root actually
            ##some code
            (#val1, val2, val3, val4 are some computed values)
            stack.append([val1, val2, val3, val4, all_items[4].right]) #Note, all_items[4] is root
            stack.append([val1, val2, val3, val4, all_items[4].left]) #Note, all_items[4] is root
        print(root.val)
        #It prints OLD_VALUE instead of NEW_VALUE

Its because you dont change the value of root in the while loop. you have all_items changed and stack but not root. Thats why there is no change, because you dont assign any kind of change through this variable

You are just assign the value & push into the stack outside the loop. In while loop, you are not performing any operation to set the new value of the variable root . You just pop the root value inside the loop . Thats why it show the same value inside & outside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM