python中的list.append()返回null
python中list1.append()和list1+list2之间的实际区别是什么?? 同时,为什么下面的语句返回NULLpython中的list.append()返回null,python,Python,python中list1.append()和list1+list2之间的实际区别是什么?? 同时,为什么下面的语句返回NULL print(list1.append(list2)) {其中list1和list2是2个简单列表}list.append()修改对象并返回None []+[]创建并“返回”新列表 建议阅读:返回None是一种传达操作有副作用的方式,即它正在更改操作数之一,而不是保持操作数不变并返回新值 list1.append(list2) …更改列表1,使其成为此类别的成员
print(list1.append(list2))
{其中list1和list2是2个简单列表}list.append()
修改对象并返回None
[]+[]
创建并“返回”新列表
建议阅读:返回
None
是一种传达操作有副作用的方式,即它正在更改操作数之一,而不是保持操作数不变并返回新值
list1.append(list2)
…更改列表1,使其成为此类别的成员
比较以下两段代码:
# in this case, it's obvious that list1 was changed
list1.append(list2)
print list1
……和:
# in this case, you as a reader don't know if list1 was changed,
# unless you already know the semantics of list.append.
print list1.append(list2)
禁止后者(通过使其无用)从而提高语言的可读性。打印函数时,打印它返回的内容,而append方法不返回任何内容。但是,您的列表现在有了一个新元素。您可以打印列表以查看所做的更改
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.append(b) # append just appends the variable to the next index and returns None
>>> print a
[1,2,3,[4,5,6]]
>>> a.extend(b) # Extend takes a list as input and extends the main list
[1,2,3,4,5,6]
>>> a+b # + is exactly same as extend
[1,2,3,4,5,6]
list1+list2
表示将两个列表合并为一个大列表
list1.append(element)
在列表末尾添加一个元素
下面是一个append vs的示例+
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>>
>>> a.append(b)
>>> a
[1, 2, 3, [4, 5, 6]]
请注意,
.append
与将两个列表添加在一起有很大的不同,但是.extend
将一个列表逐个添加更为相似,只是它会改变原始列表,而不是返回新列表。