Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python updating int and list with function

Tags:

python

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]

like image 442
clement Avatar asked Mar 18 '26 20:03

clement


1 Answers

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

like image 181
Mazdak Avatar answered Mar 21 '26 08:03

Mazdak