def trick(l,i):
if i==1:
return l[0]
else:
return l[1]
def foo(x):
x[0]='def'
x[1]='abc'
return x[1]
q=['abc','def']
print (trick(q,1)==foo(q))
print (trick(q,1)==foo(q))
print (trick(q,0)== foo(q))
当我运行它时,它会打印True,False,True。但是因为foo()总是返回相同的东西,不应该是True,True,False。这些功能之一是以某种方式更改输入列表q吗?因为任何这些函数的返回应该独立于原始列表。
答案 0 :(得分:4)
鉴于Python中的list
是可变的,如果您将list
传递给方法,在幕后,您实际上将参考传递给那个list
,这意味着如果你改变了方法中的list
,那么你正在为引用该列表的每个人改变list
。
考虑一个简单的例子:
def foo(lst):
lst[0] = 3
test_list = ["hello", "world"]
print test_list # prints ['hello', 'world']
foo(test_list) # mutates `test_list` by setting `test_list[0] = 3`
print test_list # prints [3, 'world']
在你的情况下,
def trick(l,i):
if i==1:
return l[0]
else:
return l[1]
def foo(x):
x[0]='def'
x[1]='abc'
return x[1]
q=['abc','def']
# in the below line, Python first evaluates `trick(q, 1)`
# which returns 'abc'. Then Python evaluates `foo(q)`, which
# mutates `q` to `['def', 'abc']` and returns the new `q[1]`,
# or 'abc'. Therefore, this statement evaluates to `True`.
print (trick(q,1)==foo(q))
# in the below line, Python evaluates `trick(q, 1)` with the
# newly mutated `q` and so returns 'def'. `foo(q)` again modifies
# `q` to `['def', 'abc']` and returns 'abc'. Therefore, the statement
# evaluates to `False`.
print (trick(q,1)==foo(q))
# this last statement evaluates to True because `trick(q, 0)` returns
# 'def', which is the same as what `foo(q)` returns.
print (trick(q,0)== foo(q))