2008年6月20日 星期五

in-place changes & non in-place changes

non in-place change:
for immutable object, such as number & string
ex:
a=3
b=a
b=2
--->  a=3 ,  b=2

in-place  changes:
for list , dictionary , etc
ex:
a=[1,2,3]
b=a
b[0]=5
--->  a=[5,2,3],  b=[5,2,3]


note:
a=[1,2]
b=a
b=[3,4]
--->  a is still [1,2]  because now  b & a point to different objects

the parameter of the function is passed by assignment 
Hence, it is the same.
If parameter is mutable, it can be changed
If parameter is not mutable, it can not be changed

how to change non-mutable argument for caller:
using return value
def  test(x, y)
     x=3
     y= 3
     return x, y
a=2
b=2
a, b= test(a, b)


沒有留言: