Why does append() always return None in Python?(为什么 append() 在 Python 中总是返回 None?)
问题描述
list = [1, 2, 3]
print(list.append(4)) ## WRONG, print does not work, append() returns None
## RIGHT:
list.append(4)
print(list) ## [1, 2, 3, 4]
我正在学习 Python,我不确定这个问题是否特定于语言以及 append
在 Python 中是如何实现的.
I'm learning Python and I'm not sure if this problem is specific to the language and how append
is implemented in Python.
推荐答案
append
是一个变异(破坏性)操作(它修改列表而不是返回一个新列表).进行 append
的非破坏性等效的惯用方法是
append
is a mutating (destructive) operation (it modifies the list in place instead of of returning a new list). The idiomatic way to do the non-destructive equivalent of append
would be
l = [1,2,3]
print l + [4] # [1,2,3,4]
print l # [1,2,3]
回答你的问题,我的猜测是如果append
返回新修改的列表,用户可能会认为它是非破坏性的,即他们可能会编写类似的代码
to answer your question, my guess is that if append
returned the newly modified list, users might think that it was non-destructive, ie they might write code like
m = l.append("a")
n = l.append("b")
并期望 n
为 [1,2,3,"b"]
这篇关于为什么 append() 在 Python 中总是返回 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 append() 在 Python 中总是返回 None?


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01