Reputation: 71
I am new at Python and wonder how a function can act on variables and collections. I do not understand why my update_int function cannot update an int whereas update_list can?
def update_int(i):
i = 1
i = 0
update_int(i)
print i
returns 0
def update_list(alist):
alist[0] = 1
i = [0]
update_list(i)
print i
returns [1]
Upvotes: 3
Views: 683
Reputation: 107307
Because changing a mutable object like list
within a function can impact the caller and its not True for immutable objects like int
.
So when you change the alist
within your list you can see the changes out side of the functions too.But note that it's just about in place changing of passed-in mutable objects, and creating new object (if it was mutable) doesn't meet this rules!!
>>> def update_list(alist):
... alist=[3,2]
...
>>> l=[5]
>>> update_list(l)
>>> l
[5]
For more info read Naming and Binding In Python
Upvotes: 3