[英]a=list().append(“hello”) vs a=list(); a.append(“hello”) in python?
我有
try:
a = list().append('hello')
但是a
是NoneType
try:
b = list()
b.append('hello')
和b
是list
類型
我認為list()
返回一個列表對象, list().append('hello')
將使用返回列表做追加,但為什么是價值a
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']
a = list().append('hello')
上面一行,將創建一個新的列表,然后調用append()
方法,只是返回代碼存儲append()
給變量a
。 由於值為None
,因此只表示append()
方法沒有返回值。
要確認這一點,您可以嘗試這樣做:
>>> a = list()
>>> result = a.append('hello')
>>> print a
['hello']
>>> print result
None
你已經得到了問題的答案,但我只是指出,做你想要做的事情的最好辦法是。 它應該是:
a = [ 'hello' ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.