I am a Network Engineer trying to learn Python programming as a job requirement.
I wrote this code below to
# Funtion to chop the first and last item in the list
def chop(t):
t.pop(0) and t.pop(len(t)-1)
return t
When I run the function on the list t and assign it to a variable a. a gets the remainder of the list after the function was executed and a becomes a new list.This works perfect.
>>> t = ['a', 'b', 'c', 'd', 'e' ,'f','g','h','i','j','k','l']
>>> a=chop(t)
>>> a
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
>>>
Later when i try it works well but the value of a also changes to the output of print chop(t) whereas I did not run the variable a through the function chop(t). Can someone explain why does this happen?
>>> print chop(t)
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> a
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Regards Umesh
aandtrefer to the same list. If you alter one, they are both being altered.chopfunction mutates the list object that you pass to it, and returns that same list object. So the assignmenta = chop(t)makesaanother name for the same list object that is also namedt, just as if you'd donea = t.t[1:-1]