You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python remove方法为何会改变其他关联变量?

为什么修改thislist后xx也跟着变?

这是因为Python里的列表属于可变对象,赋值操作xx = thislist并没有复制列表的内容,只是让xx和thislist指向内存中同一个列表对象。打个比方,就像给同一个房间装了两扇门,不管走哪扇门进去,看到的都是同一个房间里的东西。

你代码里的执行逻辑是:

  1. 创建列表["apple", "banana", "cherry"],thislist指向这个对象
  2. xx=thislist后,xx也指向同一个列表对象
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 06:23:12