我注意到,许多修改列表内容的列表操作将返回 None,而不是返回列表本身。示例:>>> mylist = ['a', 'b', 'c']>>> empt...
我注意到,许多修改列表内容的列表操作都会返回 None
,而不是返回列表本身。示例:
>>> mylist = ['a', 'b', 'c']
>>> empty = mylist.clear()
>>> restored = mylist.extend(range(3))
>>> backwards = mylist.reverse()
>>> with_four = mylist.append(4)
>>> in_order = mylist.sort()
>>> without_one = mylist.remove(1)
>>> mylist
[0, 2, 4]
>>> [empty, restored, backwards, with_four, in_order, without_one]
[None, None, None, None, None, None]
这个决定背后的想法是怎样的?
在我看来,这似乎是一种阻碍,因为它阻止了列表处理的“链接”(例如 mylist.reverse().append('a string')[:someLimit]
)。我想可能是“当权者”认为列表理解是一种更好的范例(一种有效的观点),因此不想鼓励其他方法 - 但阻止直观的方法似乎有悖常理,即使存在更好的替代方案。
This question is specifically about Python's design decision to return None
from mutating list methods like .append
. However, novices often write incorrect code that expects .append
(in particular) to return the same list that was just modified. Please do close such questions as a duplicate of this one, however. "The code did the wrong thing because the result was None
rather than the list" is something that the OP in these cases should have discovered independently via debugging; creating a proper MRE leaves behind a question like this one - therefore, it can be considered a duplicate.
See 如何将重复计算的结果收集到列表、字典等中(或复制每个元素均经过修改的列表)? for the simple question of " how do I append to a list repeatedly?" (or debugging questions that boil down to that problem). This is a new canonical that has been specifically prepared to address the topic with the perspective that beginners lack.
要获取列表的修改版本,请参阅:
.extend
)
.remove
)
The same issue applies to some methods of other built-in data types, e.g. set.discard
(see 如何使用列表推导从列表内的集合中删除特定元素 ) and dict.update
(see 为什么 python dict.update() 不返回对象? ).
The same reasoning applies to designing your own APIs. See 让就地操作返回对象是不是一个坏主意? .