Python variable assignment changes value -


i network engineer trying learn python programming job requirement.

i wrote code below

# funtion chop first , last item in list

def chop(t):     t.pop(0) , t.pop(len(t)-1)     return t 

when run function on list t , assign variable a. gets remainder of list after function executed , becomes new list.this works perfect.

>>> t = ['a', 'b', 'c', 'd', 'e' ,'f','g','h','i','j','k','l'] >>> a=chop(t) >>> ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] >>>  

later when try works value of changes output of print chop(t) whereas did not run variable through function chop(t). can explain why happen?

>>> print chop(t) ['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] >>> ['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

regards umesh

to save unmodified list t, create copy of a = t[:], , test chop on list a

>>> t = ['a', 'b', 'c', 'd', 'e' ,'f','g','h','i','j','k','l'] >>> a=t[:] >>> a.pop(0) 'a' >>> ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] >>> t ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] >>>  

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -