extend、append函数详解
一、列表
1>append()函数
a.append(b):是将b原封不动的追加到a的末尾上,会改变a的值,其中,b可为列表、元组、字符串、一串数/字符/字符串
①列表
a = [1,2,3]
b = [4,5]
a.append(b)
print(a) #输出:[1, 2, 3, [4, 5]]
②元组
a = [1,2,3]
b = (4,5)
a.append(b)
print(a) #输出:[1, 2, 3, (4, 5)]
③字符串
a = [1,2,3]
b = 'string'
a.append(b)
print(a) #输出:[1, 2, 3, 'string']
④一串数/字符/字符串
会将b转化为元组追加到a的末尾上
(1)一串数
a = [1,2,3]
b = 4,5
a.append(b)
print(a) #输出:[1, 2, 3, (4, 5)]
(2)一串字符
a = [1,2,3]
b = 'l','a','n'
a.append(b)
print(a) #输出:[1, 2, 3, ('l', 'a', 'n')]
(3)一串字符串
a = [1,2,3]
b = 'lan','tian'
a.append(b)
print(a) #输出:[1, 2, 3, ('lan', 'tian')]
2>extend()函数
a.extend(b):是将b拆开后追加到a的末尾上,会改变a的值,其中,b可为列表、元组、字符串、一串数/字符/字符串
①列表
a = [1,2,3]
b = [4,5]
a.extend(b)
print(a) #输出:[1, 2, 3, 4, 5]
②元组
a = [1,2,3]
b = (4,5)
a.extend(b)
print(a) #输出:[1,2,3,4,5]
③字符串
a = [1,2,3]
b = 'lantian'
a.extend(b)
print(a) #输出:[1, 2, 3, 'l', 'a', 'n', 't', 'i', 'a', 'n']
④一串数/字符/字符串
(1)一串数
a = [1,2,3]
b = 4,5
a.extend(b)
print(a) #输出:[1, 2, 3, 4, 5]
(2)一串字符
a = [1,2,3]
b = 'l','a','n','t','i','a','n'
a.extend(b)
print(a) #输出:[1, 2, 3, 'l', 'a', 'n', 't', 'i', 'a', 'n']
(3)一串字符串
a = [1,2,3]
b = 'lan','tian','n'
a.extend(b)
print(a) #输出:[1, 2, 3, 'lan', 'tian', 'n']