关于python:为什么append在这段代码中没有返回?

Why does append return none in this code?

1
2
3
4
5
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中实现append。


append是一种变异(破坏性)操作(它在适当位置修改列表,而不是返回新列表)。与append进行无损等效的惯用方法是

1
2
3
l = [1,2,3]
print l + [4] # [1,2,3,4]
print l # [1,2,3]

为了回答你的问题,我猜如果append返回新修改的列表,用户可能会认为它是非破坏性的,即他们可能会编写类似

1
2
m = l.append("a")
n = l.append("b")

预计n[1,2,3,"b"]


在python中,突变序列的方法返回None是一种约定。

考虑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> a_list = [3, 2, 1]
>>> print a_list.sort()
None
>>> a_list
[1, 2, 3]

>>> a_dict = {}
>>> print a_dict.__setitem__('a', 1)
None
>>> a_dict
{'a': 1}

>>> a_set = set()
>>> print a_set.add(1)
None
>>> a_set
set([1])

从Python3.3开始,现在更明确地记录了这一点:

Some collection classes are mutable. The methods that add, subtract,
or rearrange their members in place, and don’t return a specific item,
never return the collection instance itself but None.

设计和历史常见问题解答给出了此设计决策背后的理由(关于列表):

Why doesn’t list.sort() return the sorted list?

In situations where performance matters, making a copy of the list
just to sort it would be wasteful. Therefore, list.sort() sorts the
list in place. In order to remind you of that fact, it does not return
the sorted list. This way, you won’t be fooled into accidentally
overwriting a list when you need a sorted copy but also need to keep
the unsorted version around.

In Python 2.4 a new built-in function – sorted() – has been added.
This function creates a new list from a provided iterable, sorts it
and returns it.


建议之一是避免使用关键字或函数作为变量名。在上面的代码中,使用list作为变量:

1
list = [1, 2, 3]

我建议不要使用list作为变量名,因为列表实际上已经定义为内置类型。正如蔡塞松和斯奎盖指出的那样,那时的情况已经不多了。

1
2
3
l = [1, 2, 3]
l.append(4)
print l  ## [1, 2, 3, 4]


它不返回任何内容。它附加/添加到变量中,以查看您是否应该使用第一个用于在打印中附加的变量

1
2
3
friends=["Rajendra V"]
friends.append("John")
print(friends)