You need to enable JavaScript to run this app. Python调用pop函数删除列表元素时报TypeError错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Python调用pop函数删除列表元素时报TypeError错误如何解决?

问题原因

你调用pop()方法时错误使用了方括号[],在Python中:

  • 方括号[]用于索引、切片、取下标操作,仅适用于支持下标访问的对象(比如列表、元组、字典)
  • 方法/函数调用必须使用圆括号()传参,list.pop是列表的内置方法,所以不能用[]传入索引参数。

额外说明:Python的列表索引从0开始计数,你当前填的参数4对应的是列表第5个元素,如果你确实要移除第4个值为queen bed的元素,需要把参数改为3。

修正后代码

inventory = ["twin bed", "twin bed", "headboard", "queen bed", "king bed", "dresser",
             "dresser", "table", "table", "nightstand", "nightstand", "king bed",
             "king bed", "twin bed", "twin bed", "sheets", "sheets", "pillow",
             "pillow"]

# 移除索引为4的元素就保留参数4,移除第4个元素改为参数3
removed_item = inventory.pop(4)
print(removed_item)

内容的提问来源于stack exchange,提问作者Chantel Segreti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:15:04