3

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]

clement
  • 71
  • 5
  • to change variable in function you can use `global i` , without passing it to the function and it doesn't work because with variable you work on "copy" of that variable – Aleksander Monk Jun 04 '15 at 08:54
  • possible duplicate of [In Python, why can a function modify some arguments as perceived by the caller, but not others?](http://stackoverflow.com/questions/575196/in-python-why-can-a-function-modify-some-arguments-as-perceived-by-the-caller) – Andrzej Pronobis Jun 04 '15 at 09:01

1 Answers1

3

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

Mazdak
  • 105,000
  • 18
  • 159
  • 188