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

调用列表remove()方法后出现TypeError: NoneType无len()错误的原因

为什么调用remove()后会出现NoneType错误?

你遇到的这个错误,核心是对Python列表的remove()方法的返回值理解错啦!

问题根源

list.remove()是一个原地修改列表的方法——它会直接在你原来的list_of_directions列表里删除指定的元素,但这个方法本身的返回值是None,而不是修改后的列表。你把它的返回值赋值给了new_list,那new_list自然就变成了None,而None是没有长度属性的,所以调用len(new_list)就会抛出TypeError: object of type 'NoneType' has no len()这个错误。

正确的写法

根据你的需求,有两种解决方式:

  1. 如果需要保留原列表,先复制再删除:
list_of_directions = ['right', 'left', 'up', 'down']
new_list = list_of_directions.copy()  # 先复制原列表到新变量
new_list.remove('right')
print(len(new_list))  # 输出 3
  1. 如果不需要保留原列表,直接操作原列表后取长度:
list_of_directions = ['right', 'left', 'up', 'down']
list_of_directions.remove('right')
print(len(list_of_directions))  # 输出 3

小提醒

Python里很多列表的原地修改方法(比如sort()、append()、extend())都是返回None,这是个很容易踩的小坑,记住这个特性以后就不会再犯类似的错误啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:35:03