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。
1 2 3 | l = [1,2,3] print l + [4] # [1,2,3,4] print l # [1,2,3] |
为了回答你的问题,我猜如果
1 2 | m = l.append("a") n = l.append("b") |
。
预计
在python中,突变序列的方法返回
考虑:
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 butNone .
号
设计和历史常见问题解答给出了此设计决策背后的理由(关于列表):
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] |
我建议不要使用
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) |
。