Python update and list with function

I'm new to Python and wondering how a function can act on variables and collections. I don't understand why my update_int function cannot update an int, while 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]

+3


source to share


1 answer


Since changing a mutable object such as list

inside a function can affect the caller and its not True for immutable objects such as int

.

So when you change alist

in your list, you might also see changes aside from functions. Note that it just replaces the mutable objects with the change and creates a new object (if it was mutable) does not follow these rules !!



>>> def update_list(alist):
...   alist=[3,2]
... 
>>> l=[5]
>>> update_list(l)
>>> l
[5]

      

For more details read Naming and Binding in Python

+3


source







All Articles