为什么在这个code并追加返回没有? [英] Why does append return none in this code?

查看:115
本文介绍了为什么在这个code并追加返回没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list = [1, 2, 3]
print list.append(4)   ## NO, does not work, append() returns None
## Correct pattern:
list.append(4)
print list  ## [1, 2, 3, 4]

我正在学习Python和我不知道如果这个问题是特定于语言和追加如何用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 is a 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]

要回答你的问题,我的猜测是,如果追加返回新修改的列表中,用户可能会认为这是无损的,即它们可以写$ C $ ç像

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]

这篇关于为什么在这个code并追加返回没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆