Hongzhi Hongzhi - 7 months ago 10
Python Question

python:use a function to remove a list element,I get confused with the result

def testf(st):
st=st[1:]
print st
def popf(st):
st.pop(0)
print st
a = ["response", ["wis", "hello"], ["deng", "shen"]]
testf(a)
print a
a=["response",["wis","hello"],["deng","shen"]]
popf(a)
print a


Below is the output:

[['wis', 'hello'], ['deng', 'shen']]
['response', ['wis', 'hello'], ['deng', 'shen']]
[['wis', 'hello'], ['deng', 'shen']]
[['wis', 'hello'], ['deng', 'shen']]


I want to use a function to delete a list element, but I'm confused why the function
testf()
can't delete the element after the function but the
popf()
function can do. what's the difference? if not in the function,
st=st[1:] = st.pop(0)
(
del st[0]
also works).

AKS AKS
Answer

In first function you are assigning a new value to st in this statement so it is a completely new variable and not the one passed as the argument:

st = st[1:]

You can check it using id before and after assignment:

In [13]: def testf(st):
   ....:     print('before: ', id(st))
   ....:     st = st[1:]
   ....:     print('after: ', id(st))
   ....:

In [14]: a = ["response", ["wis", "hello"], ["deng", "shen"]]

In [15]: id(a)
Out[15]: 85287112L

In [16]: testf(a)
('before: ', 85287112L)
('after: ', 85289480L)

But in the second function there is no assignment hence the id remains same. It means you modified the list passed in the arguments:

In [17]: def popf(st):
   ....:     print('before: ', id(st))
   ....:     st.pop(0)
   ....:     print('after: ', id(st))
   ....:

In [18]: popf(a)
('before: ', 85287112L)
('after: ', 85287112L)
Comments