append和expend函数区别

一、列表

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 = 'f','e','n'
a.append(b)
print(a)   #输出:[1, 2, 3, ('f', 'e', 'n')]

(3)一串字符串

a = [1,2,3]
b = 'fen','he'
a.append(b)
print(a)   #输出:[1, 2, 3, ('fen', 'he')]

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 = 'fenhe'
a.extend(b)
print(a)     #输出:[1, 2, 3, 'f', 'e', 'n', 'h', 'e']

④一串数/字符/字符串
(1)一串数

a = [1,2,3]
b = 4,5
a.extend(b)
print(a)   #输出:[1, 2, 3, 4, 5]

(2)一串字符

a = [1,2,3]
b = 'f','e','n','h','e'
a.extend(b)
print(a)   #输出:[1, 2, 3, 'f', 'e', 'n', 'h', 'e']

(3)一串字符串

a = [1,2,3]
b = 'fen','he','k'
a.extend(b)
print(a)   #输出:[1, 2, 3, 'fen', 'he', 'k']

二、字符串和元组中都没有append()和extend()函数

你可能感兴趣的:(python,开发语言)