Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python confusing function reference

Can anyone explain to me why the two functions below a and b are behaving differently. Function a changes names locally and b changes the actual object.

Where can I find the correct 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']
like image 356
sajith Avatar asked Aug 10 '14 07:08

sajith


1 Answers

Assigning to parameter inside the function does not affect the argument passed. It only makes the local variable to reference new object.

While, list.append modify the list in-place.

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

def a(names):
    names[:] = ['Fred', 'George', 'Bill']
like image 181
falsetru Avatar answered Sep 28 '22 00:09

falsetru