在列表上使用 remove() 后"TypeError: object of type 'NoneType' has no len()"



我有这个代码:

list_of_directions = ['right', 'left', 'up', 'down']
new_list = list_of_directions.remove('right')
print(len(new_list))

但是我收到错误消息

类型

错误:类型为"NoneType"的对象没有 len((

我以为我明白.remove()是如何工作的,但也许我没有?

为什么我会收到此错误?

list.remove是一个就地操作。它返回None.

您需要在单独的行中执行此操作以new_list。换句话说,而不是new_list = list_of_directions.remove('right')

new_list = list_of_directions[:]
new_list.remove('right')    

在上面的逻辑中,我们在删除特定元素之前将new_list分配给list_of_directions的副本。

请注意分配给list_of_directions副本的重要性。这是为了避免new_list以不希望的方式随list_of_directions变化的极有可能的情况。

您看到的行为在文档中明确指出:

您可能已经注意到,像insertremovesort仅修改列表没有打印返回值 - 它们返回 默认None。这是所有可变数据的设计原则 Python 中的结构。

最新更新