0

I am having issues understanding how global variables can or cannot be edited within the local scope of functions, please see the two example codes I have provided which contrast eachother:

Example 1

    def function():
        x[0] = True
    x = [False] # global variable
    function()
    print(x)  # True

Example 2

    def function():
        z = True
    z = False # global variable
    function()
    print(z)  # False

I was of the understanding that global variables cannot be edited within a local scope (inside a function) unless they are explicitly called globally i.e (global "variable_name"), however example 1 indicates that when dealing with lists and using the append method, I can in-fact edit the real global variable without having to call it with the explicit global term. Where as in example 2, I am unable to re-assign the global variable which is contrary to example 1. Please explain why this is the case, does the append method or lists in particular interact with global/local scope rules differently?

1

1 Answer 1

1

Lists are mutable, so while the variable can not be edited (assigned to another list for example) the contents of the list may be modified and the variable will still point to the same list, so the variable is untouched.

Try:

def function():
    x = [True]

x = [False] # global variable
function()
print(x)
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.