Python confusing link function

Can someone explain to me why the two functions below a and b behave differently. The function a modifies names locally, and b modifies the actual object.

Where can I find the right documentation for this behavior?

 def a(names): names = ['Fred', 'George', 'Bill'] def b(names): names.append('Bill') first_names = ['Fred', 'George'] print "before calling any function",first_names a(first_names) print "after calling a",first_names b(first_names) print "after calling b",first_names 

Output:

 before calling any function ['Fred', 'George'] after calling a ['Fred', 'George'] after calling b ['Fred', 'George', 'Bill'] 
+6
source share
2 answers

Function a creates a new local variable names and assigns it a list ['Fred', 'George', 'Bill'] . So now this is another variable from the global first_names , as you already learned.

You can read about changing the list inside a function here .

One way to make function a behave the same as function b is to make function a a modifier :

 def a(names): names += ['Bill'] 

Or you can make a pure function:

 def c(names): new_list = names + ['Bill'] return new_list 

And call him:

 first_names = c(first_names) print first_names # ['Fred', 'George', 'Bill'] 

A pure function means that it does not change the state of the program, that is, it does not have any side effects, such as changing global variables.

+1
source

Assigning a parameter within a function does not affect the argument passed. This allows the local variable to refer to the new object.

For now, list.append change the list in place.

If you want to change the internal function of the list, you can use the slice assignment:

 def a(names): names[:] = ['Fred', 'George', 'Bill'] 
+7
source

Source: https://habr.com/ru/post/973603/


All Articles