python 列表extend方法和+(拼接)的区别

1.extend方法会直接作用于原始列表,会修改原始列表的值

a = [10, 20, 30]
b = [1, 2, 3]

print(a + b)
print(a)
a.extend(b)
print(a)

image

2.extend接收到的参数是一个可迭代的对象(iterable),不管是list,tuple,str,dict,set

a = [10, 20, 30]
b = {"name": "张三", "age": 18}
c = {"盖伦", "金克斯", "奥拉夫"}
d = "hello"
e = (66, 88, 99)
f = [100, 200, 300]

a.extend(b)
a.extend(c)
a.extend(d)
a.extend(e)
a.extend(f)
print(a)

image

3.+ 拼接只能是列表+列表的形式,如果拼接的对象不是列表就会报错

a = [10, 20, 30]
b = {"name": "张三", "age": 18}
c = {"盖伦", "金克斯", "奥拉夫"}
d = "hello"
e = (66, 88, 99)
f = [100, 200, 300]

a.extend(b)
a.extend(c)
a.extend(d)
a.extend(e)
a.extend(f)
print(a)
print(a+e)  # 会报错

image

posted @ 2023-08-30 16:37  弩哥++  阅读(74)  评论(0编辑  收藏  举报