一、添加的数据类型不同
list.append(object) # 向列表中添加一个对象object
list.extend(sequence) # 把一个序列seq的内容添加到列表中
append()
可以添加一切数据类型,Python万物皆对象
extend()
只能添加可迭代对象
a = [1, 2, 3]
b = 4
c = [5, 6, 7]
d = "s"
e = "svip"
f = ["hehe", "haha"]
g = ("hua", "guo")
h = {"name": "xiaoming"}
a.append(b)
a.append(c)
a.append(d)
a.append(e)
a.append(f)
a.append(g)
a.append(h)
print a
# [1, 2, 3, 4, [5, 6, 7], 's', 'svip', ['hehe', 'haha'], ('hua', 'guo'), {'name': 'xiaoming'}]
a.extend(b)
Traceback (most recent call last):
File "/Users/gaoyueyun/Documents/code/machine_test/practice_test.py", line 97, in <module>
a.extend(b)
TypeError: 'int' object is not iterable
# [1, 2, 3, 5, 6, 7, 's', 's', 'v', 'i', 'p', 'hehe', 'haha', 'hua', 'guo', 'name']
二、添加后结果不同
list.append(object) # 会将整个对象添加进list
list.extend(sequence) # 把一个序列拆分后添加到列表中
a = [1, 2, 3]
c = [5, 6, 7]
d = "s"
g = ("hua", "guo")
h = {"name": "xiaoming"}
1、添加列表
a.append(c)
print a # [1, 2, 3, [5, 6, 7]]
a.extend(c)
print a # [1, 2, 3, [5, 6, 7], 5, 6, 7]
2、添加字符串
# 添加单个字符没有区别
a.append(d)
print a # [1, 2, 3, 's']
a.extend(d)
print a # [1, 2, 3, 's', 's']
a.append(e)
print a # [1, 2, 3, 'svip']
a.extend(e)
print a # [1, 2, 3, 'svip', 's', 'v', 'i', 'p']
3、添加元组
a.append(g)
print a # [1, 2, 3, ('hua', 'guo')]
a.extend(g)
print a # [1, 2, 3, ('hua', 'guo'), 'hua', 'guo']
4、添加字典
a.append(h)
print a # [1, 2, 3, {'name': 'xiaoming'}]
a.extend(h)
print a # [1, 2, 3, {'name': 'xiaoming'}, 'name']
extend()添加字典时只能添加到字典的“key”
三、都是对原有列表进行扩容,没有返回值,无法赋值给变量
a = [1, 2, 3]
b = 4
c = [5, 6, 7]
d = "s"
e = "svip"
f = ["hehe", "haha"]
g = ("hua", "guo")
h = {"name": "xiaoming"}
print id(a) # 4312016608
a.append(h)
print id(a) # 4312016608
a.extend(h)
print id(a) # 4312016608
print a.append(c) # None
print a.extend(c) # None
t = a.append(c)
print t # None
s = a.extend(c)
print s # None
四、参考文档
1、https://www.cnblogs.com/subic/p/6553187.html
2、https://www.cnblogs.com/wushuaishuai/p/7729011.html
3、https://www.cnblogs.com/xuchunlin/p/5479119.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)