Search code examples
pythonlistbooleannested-function

How to flip the boolean value in a nested function


I have a problem regarding flipping the boolean value. I'd like to do the flip inside another function. The code is similar to this one:

def printChange():
    isChange = [True]
    change(isChange)
    print(isChange)

def change(x):
    x = [False]

printChange() # [True]

If I modify the change function like this:

def printChange():
    isChange = [True]
    change(isChange)
    print(isChange)

def change(x):
    x[0] = False

printChange() #[False]

I am curious about why this happens. I guess it should be related to some mutability stuff. Thank you!


Solution

  • You are modifying the local value x in not isChange this function:

    def change(x):
        x = [False]
    

    You need to return the desired value:

    def change(x):
        return [False]
    

    Or better yet if you want to flip the value:

    def change(x):
        return [not x[0]]
    

    Then in printChange you need to assign the return value to isChange:

    def printChange():
        isChange = [True]
        isChange = change(isChange)
        print(isChange)