list append()和extend()区别
2019-04-24 本文已影响0人
脏脏包盛
append()
- 添加单一元素在末尾
my_list = ['geeks', 'for']
my_list.append('geeks')
print(my_list)
output:
['geeks', 'for', 'geeks']
- 添加一个list后,也是只添加一个list对象
my_list = ['geeks', 'for', 'geeks']
another_list = [6, 0, 4, 1]
my_list.append(another_list)
print(my_list)
output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]
extend()
- 迭代的添加每一个元素到list中,如果添加一个list则会添加list中元素个数的数量元素
my_list = ['geeks', 'for']
another_list = [6, 0, 4, 1]
my_list.extend(another_list)
print(my_list)
outputs:
['geeks', 'for', 6, 0, 4, 1]
my_list = ['geeks', 'for']
another_list = [6, 0, 4, [1, 2]]
my_list.extend(another_list)
print(my_list)
output:
['geeks', 'for', 6, 0, 4, [1, 2]]
- 字符串是iterable,所以会添加每一个字符到list中
my_list = ['geeks', 'for', 6, 0, 4, 1]
my_list.extend('geeks')
print(my_list)
outputs:
['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']