list append() ---》添加一個對象整體
extend()? ----》添加迭代的對象
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']