Home > OS >  Why is the local variable updating a variable outside the function?
Why is the local variable updating a variable outside the function?

Time:05-09

Is there any reason to why h_local is updating h_global?

def func(n, h_local):
    if n > len(h_local) - 1:
        h_local.extend([0 for i in range(n - (len(h_local) - 1))])


h_global = [0, 2, 5, 6, 9]
func(8, h_global)
print(h_global)

CodePudding user response:

def func(n, h_local):

Have you ever programmed with C/C ? Do you know what does it mean that an object is passed by reference?

In this case h_local is an argument of a mutable type, which in Python is treated as if it was passed by reference.


In C you may see something like this:

void function(int passed_by_value, int& passed_by_reference) {
    passed_by_value  ;
    passed_by_reference  ;
}

In this case, when calling function on two variables, the first argument won't be changed, while the second one will.

In Python you don't have the passage for reference, but you have the mutable types. When you pass an instance of a mutable type to a function it's like passing it by reference.


You can find an explaination here, try doing the same thing as you are doing but using an immutable type, and you will see the original variable passed to the function won't be changed at the end.


That is, if you pass an immutable value, the parameter still references the exact same object (no copy is made); that fact that you can't change it is inherent in the object itself, not in how it was passed to the function.

This is the most correct explaination of why you can't do this with immutable type objects.

CodePudding user response:

Python variables are just names that refer to objects. h_global and h_local are two different names (in different scopes) that refer to the same list ([0, 2, 5, 6, 9]) that was first created when the name h_global was defined.

When the function is called, it essentially performs the following assignment:

h_local = h_global

which just makes h_local another name for the list h_global already refers to.

Inside the function, the extend methods adds values to that list; which name is used to invoke the method is irrelevant.

  • Related