Python remove方法为何会改变其他关联变量?
为什么修改thislist后xx也跟着变?
这是因为Python里的列表属于可变对象,赋值操作xx = thislist并没有复制列表的内容,只是让xx和thislist指向内存中同一个列表对象。打个比方,就像给同一个房间装了两扇门,不管走哪扇门进去,看到的都是同一个房间里的东西。
你代码里的执行逻辑是:
- 创建列表
["apple", "banana", "cherry"],thislist指向这个对象 xx=thislist后,xx也指向同一个列表对象thislist.remove("banana")直接修改了这个列表对象本身,所以不管用thislist还是xx访问,结果都是修改后的列表
如果想让xx保留原列表的内容,需要对列表做浅拷贝,常用方法有三种:
- 切片语法:
xx = thislist[:] - 用list构造器:
xx = list(thislist) - 使用copy模块:
import copy; xx = copy.copy(thislist)
修改后的代码示例:
thislist = ["apple", "banana", "cherry"] xx = thislist[:] # 执行浅拷贝 thislist.remove("banana") print(f"thislist={thislist}") print(f"xx={xx}")
运行后输出:
thislist=['apple', 'cherry'] xx=['apple', 'banana', 'cherry']
内容的提问来源于stack exchange,提问作者vince
相关产品推荐
相关产品推荐

