调用列表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()这个错误。
正确的写法
根据你的需求,有两种解决方式:
- 如果需要保留原列表,先复制再删除:
list_of_directions = ['right', 'left', 'up', 'down'] new_list = list_of_directions.copy() # 先复制原列表到新变量 new_list.remove('right') print(len(new_list)) # 输出 3
- 如果不需要保留原列表,直接操作原列表后取长度:
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
相关产品推荐
相关产品推荐

