为了账号安全,请及时绑定邮箱和手机立即绑定

在Python中,“。append()”和“+ = []”之间有什么区别?

在Python中,“。append()”和“+ = []”之间有什么区别?

红颜莎娜 2019-08-26 11:09:35
在Python中,“。append()”和“+ = []”之间有什么区别?有什么区别:some_list1 = [] some_list1.append("something")和some_list2 = [] some_list2 += ["something"]
查看完整描述

3 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

append()方法将单个项添加到现有列表中。它不会返回新列表,而是修改原始列表。

some_list1 = []some_list1.append("something")

所以这里some_list1将被修改。

而使用+来组合列表元素会返回一个新列表。

some_list2 = []some_list2 += ["something"]

所以这里some_list2和[“something”]是两个合并的列表,并返回一个新的列表,分配给some_list2


查看完整回答
反对 回复 2019-08-26
?
holdtom

TA贡献1805条经验 获得超10个赞

让我们先举个例子


list1=[1,2,3,4]

list2=list1     (that means they points to same object)


if we do 

list1=list1+[5]    it will create a new object of list

print(list1)       output [1,2,3,4,5] 

print(list2)       output [1,2,3,4]


but if we append  then 

list1.append(5)     no new object of list created

print(list1)       output [1,2,3,4,5] 

print(list2)       output [1,2,3,4,5]


extend(list) also do the same work as append it just append a list instead of a 

single variable 


查看完整回答
反对 回复 2019-08-26
  • 3 回答
  • 0 关注
  • 2482 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信