python - Why does my function call affect my variable sent in the parameter? -
so part of /r/dailyprogrammer's challenge on trying out few simple tasks in new programming language, tried out python after having dabbled in slightly.
there had recreate bubble-sort in python , came with:
def bubble(unsorted): length = len(unsorted) issorted = false while not issorted: issorted = true in range(0, length-1): if(unsorted[i] > unsorted[i+1]): issorted = false holder = unsorted[i] unsorted[i] = unsorted[i+1] unsorted[i+1] = holder mylist = [5,6,4,2,10,1] bubble(mylist) print mylist
now code works flawlessly far can tell, , precisely problem. can't figure out why bubble function affect variable mylist without me returning it, or setting anew.
this bugging me it's python type thing :) or i'm silly man indeed.
i'm not sure reason of confusion is, if think each time when write func(obj) whole object copied stack, you're wrong.
all parameters, except primitive types such numbers, passed reference. means object's members or array elements can updated after function executed.
write simple prog confirm that:
>>> a=[1] >>> def f(x): ... x[0]=2 ... >>> f(a) >>> print a[0] 2
i hope it'll clarify picture.
for primitive types you'll have different result though:
>>> i=1 >>> def f(x): ... x=2 ... >>> f(i) >>> print 1 >>>
Comments
Post a Comment