The reason for this difference is due to the way Python names contain names. If you are inside the function definition ( def foo(): and you ACCESS the name ( VAR1 or LISTL ), it will first look for your local namespace, where it will not find anything, and then it will look for the module namespace the function was defined , up to the global namespace, until it finds a match or works.
However, ACCESS to a name and APPOINTMENT of a name are two different concepts. If you are again in the definition of your function, and you say VAR1 = 2 , you declare a new variable with the new local name VAR1 inside the function. This makes sense when you consider that otherwise you would encounter all sorts of name collisions if such a namespace werenβt at work.
When you add to the list, you are simply ACCESSIBLE to the list, and then call the method on it, which is important to change its conceptual meaning. When you use do += , you are actually assigning a value to the name.
If you want to assign values ββto names defined outside the current namespace, you can use the global . In this case, as part of your function, you will first say global VAR1 , and from there the name VAR1 will be the name in the external namespace, and any assignments to it will operate outside the function.
source share