为什么Python中的某些列表方法只能与定义的变量一起使用? [英] Why do some list methods in Python work only with defined variables?

查看:82
本文介绍了为什么Python中的某些列表方法只能与定义的变量一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]

但是:

>>> [1, 2, 3].append(4)
>>>

为什么在Python中使用 list 方法(例如insertappend)仅适用于已定义的变量?

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屋!

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