a = [1, 2, 3, 9, 10]
b = [4, 5, 6, 7, 8]
c = a[:3] + b + a[3:]
print(c)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
fruit = ['pineapple','pear']
fruitlist = ['grape', 'uuu', 'ccc']
for x in fruitlist:
fruit.insert(len(fruit),x) # len(fruit)表示根據fruit的長度動態插入
fruit
fruit = ['pineapple','pear']
fruitlist = ['grape', 'uuu', 'ccc']
for x in fruitlist:
fruit.append(x)
fruit
extend()方法添加元素,extend() 和 append() 的不同之處在於:extend() 不會把列表或者元祖視為一個整體,而是把它們包含的元素逐個添加到列表中。
l = ['Python', 'C++', 'Java']
#追加元素
l.extend('C')
print(l)
#追加元組,元祖被拆分成多個元素
t = ('JavaScript', 'C#', 'Go')
l.extend(t)
print(l)
#追加列表,列表也被拆分成多個元素
l.extend(['Ruby', 'SQL'])
print(l)
[‘Python’, ‘C++’, ‘Java’, ‘C’]
[‘Python’, ‘C++’, ‘Java’, ‘C’, ‘JavaScript’, ‘C#’, ‘Go’]
[‘Python’, ‘C++’, ‘Java’, ‘C’, ‘JavaScript’, ‘C#’, ‘Go’, ‘Ruby’, ‘SQL’]