Why python arguments change sometimes? -


this code type. here value of int has not changed outside of function value of list has changed.i expecting value of list not change. reason?

>>> def p1(list1):     list1[0]=1000  >>> def p2(i):     i+=10  >>> li=[1,2,3,4,5] >>> int1=10 >>> p1(li) >>> p2(int1) >>> li [1000, 2, 3, 4, 5] >>> int1 10 

note in p1, not assigning value list1, name of variable local p1. assigning first element of list object referenced list1, same list object referenced li in enclosing scope.

in p2, on other hand, i+=10 does assign value local variable i, not variable int1 in enclosing scope. because += operator on objects of type int not modify object, return new object instead. (that is, int, i+=10 equivalent i = + 10.)


just show += can operate on underlying object directly, consider function:

def p3(list1):     list1 += [10] 

then run on list:

>>> foo = [1,2,3] >>> p3(list1) >>> foo [1, 2, 3, 10] 

here, call list1 += [10] equivalent list1.extend([10]), not list1 = list1 + [10], due how list.__iadd__ defined. here, again not assigning value name list1, rather invoking method on object referenced list1 (which same object referenced foo).

(update: pointed out user2357112, technically do assign list1, list.__iadd__ designed assign same list back, end result still have reference same mutable object started with.)


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -