Python:为什么在我实际上不更改列表时会更改它? [英] Python: why does my list change when I'm not actually changing it?
问题描述
新手有问题,请保持谦虚:
Newbie with a question, so please be gentle:
list = [1, 2, 3, 4, 5]
list2 = list
def fxn(list,list2):
for number in list:
print(number)
print(list)
list2.remove(number)
print("after remove list is ", list, " and list 2 is ", list2)
return list, list2
list, list2 = fxn(list, list2)
print("after fxn list is ", list)
print("after fxn list2 is ", list2)
结果是:
1
[1, 2, 3, 4, 5]
after remove list is [2, 3, 4, 5] and list 2 is [2, 3, 4, 5]
3
[2, 3, 4, 5]
after remove list is [2, 4, 5] and list 2 is [2, 4, 5]
5
[2, 4, 5]
after remove list is [2, 4] and list 2 is [2, 4]
after fxn list is [2, 4]
after fxn list2 is [2, 4]
我不明白为什么仅在执行list2.remove()
而不是list.remove()
时列表会发生变化.我什至不知道要用什么搜索词来弄清楚.
I don't understand why list is changing when I am only doing list2.remove()
, not list.remove()
. I'm not even sure what search terms to use to figure it out.
推荐答案
这是因为list
和list2
在执行赋值list2=list
之后都引用了相同的列表.
That's because both list
and list2
are referring to the same list after you did the assignment list2=list
.
尝试此操作以查看它们是指的是相同的对象还是不同的对象:
Try this to see if they are referring to the same objects or different:
id(list)
id(list2)
一个例子:
>>> list = [1, 2, 3, 4, 5]
>>> list2 = list
>>> id(list)
140496700844944
>>> id(list2)
140496700844944
>>> list.remove(3)
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 4, 5]
如果您真的想创建list
的副本,以使list2
并不引用原始列表,而是引用列表的副本,请使用slice运算符:
If you really want to create a duplicate copy of list
such that list2
doesn't refer to the original list but a copy of the list, use the slice operator:
list2 = list[:]
一个例子:
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 4, 5]
>>> list = [1, 2, 3, 4, 5]
>>> list2 = list[:]
>>> id(list)
140496701034792
>>> id(list2)
140496701034864
>>> list.remove(3)
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 3, 4, 5]
此外,请勿将list
用作变量名,因为最初list
是指类型列表,但是通过定义自己的list
变量,您将隐藏引用的原始list
类型列表.示例:
Also, don't use list
as a variable name, because originally, list
refers to the type list, but by defining your own list
variable, you are hiding the original list
that refers to the type list. Example:
>>> list
<type 'list'>
>>> type(list)
<type 'type'>
>>> list = [1, 2, 3, 4, 5]
>>> list
[1, 2, 3, 4, 5]
>>> type(list)
<type 'list'>
这篇关于Python:为什么在我实际上不更改列表时会更改它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!