(Jan-15-2024, 12:02 AM)johnywhy Wrote: [ -> ]Why doesn't appending to a global list require the global
keyword, but modifying a scalar variable does?
numbers = []
dog = 5
def enter_number(x):
numbers.append(x)
global dog
dog += 1
enter_number(1)
enter_number(5)
enter_number(9)
You need to understand the scheme of how variables pass to to functions and which ones are mutable and which ones aren't and also scope. In python primitive variables are immutable. What that means is, if you say
x = 101
you cannot modify 0 and make it, lets say 1 to make 111. You have assign a new value to the variable which will overwrite existing one.
Lists, on the other hand are mutable objects, as well as dictionaries and classes and some other things. So if you have a list of [0,1,2], you can just go ahead and change a 0 in the list to some other value.
Now, about functions. Since everything in python is an object, python passes references to variables by value to functions. Here is also where scoping rules come into play. If you pass an integer to a function, you can read it. However, when you say
x = 5
inside a method, you are creating a new memory location with a local variable x and not modifying one outside of function. This why you need to use
global
keyword so that python will look up variable in the global scope.
Since lists are mutable, instead of creating a new value, you deference the list and directly modify it in the memory location it was created. However, if you actually do something like
numbers = ['x']
, it will create a local variable and won't modify the numbers in the outer scope.
Basically when you try to read a variable inside a method, python will first check local scope and then each outer scope until it either finds a variable or throws an error. If you try to write to a variable (assign), it will create one in local scope unless you specify that the variable is in the outer scope.