为什么Python中的某些列表方法只能与定义的变量一起使用? [英] Why do some list methods in Python work only with defined variables?
问题描述
>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
但是:
>>> [1, 2, 3].append(4)
>>>
为什么在Python中使用 list
方法(例如insert
和append
)仅适用于已定义的变量?
Why do list
methods in Python (such as insert
and append
) only work with defined variables?
推荐答案
在第二个示例中,没有打印任何内容,因为append
在列表中被调用(请注意实际上已执行了添加操作 ),返回None
.
In the second sample nothing is printed, because append
, that was called on a list (note that append was actually performed), returns None
.
或者,您应该提到a.append(4)
也给您一个空白行(如您的第一个示例所示),并且第一个代码示例的最终输出是a
表达式而不是a.append('4')
表达式的结果表示.
Alternatively you should mention that a.append(4)
also gave you a blank line (as your first sample shows), and final output of a first code sample was a representation of result of a
expression, not a.append('4')
expression.
在两种情况下,在append
调用之后都不会打印任何内容,因为它表示None
.
Nothing is printed after append
call in both cases because it is a representation of None
.
这篇关于为什么Python中的某些列表方法只能与定义的变量一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!