简体   繁体   中英

Using append() method on a global list in a function (Python)

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 ie (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?

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)

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