加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

a = list().append(“hello”)vs a = list();在python中a.append

发布时间:2020-12-20 12:29:56 所属栏目:Python 来源:网络整理
导读:我有 try: a = list().append('hello') 但是a是NoneType try: b = list() b.append('hello') 和b是列表类型 我认为list()返回一个列表对象,而list().append(‘hello’)将使用返回列表来追加,但为什么是None的值? 解决方法 list()确实返回一个空列表([]),但a
我有

try:
    a = list().append('hello')

但是a是NoneType

try:
    b = list()
    b.append('hello')

和b是列表类型

我认为list()返回一个列表对象,而list().append(‘hello’)将使用返回列表来追加,但为什么是None的值?

解决方法

list()确实返回一个空列表([]),但append方法在就地列表上运行 – 它更改列表本身,并且不返回新列表.它返回None.

例如:

>>> lst = []
>>> lst.append('hello')  # appends 'hello' to the list
>>> lst
['hello']
>>> result = lst.append('world')  # append method returns None
>>> result  # nothing is displayed
>>> print result
None
>>> lst  # the list contains 'world' as well now
['hello','world']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读