test = ['a', 'b', 'c', 'd']
print("未改變的數列 %s" % test)
結果:
未改變的數列 ['a', 'b', 'c', 'd']
# 增加函數 append()
# 用法
test.append('e')
test.append(['e'])
print("使用append增加 %s" % test)
結果:
使用append增加 ['a', 'b', 'c', 'd', 'e', ['e']]
# 增加函數 extend([]) 擴展的意思
# 用法
test.extend(['ab', 'ac'])
print("使用extend增加 %s" % test)
結果:
使用extend增加 ['a', 'b', 'c', 'd', 'e', ['e'], 'ab', 'ac']
# 增加函數 insert(num,'新增函數')
# 用法
test.insert(0, '我是第一')
print("使用insert 在最前增加了個我是第一 %s" % test)
結果:
使用insert 在最前增加了個我是第一 ['我是第一', 'a', 'b', 'c', 'd', 'e', ['e'], 'ab', 'ac']
# 刪除元素
# remove('一個元素的名字')
test.remove('我是第一')
print("使用remove把我是第一的元素刪除 %s" % test)
結果:
使用remove把我是第一的元素刪除 ['a', 'b', 'c', 'd', 'e', ['e'], 'ab', 'ac']
#del 刪除列表
del test[0]
print("使用del刪除列表的第一個元素 %s" % test)
結果:
使用del刪除列表的第一個元素 ['b', 'c', 'd', 'e', ['e'], 'ab', 'ac']
# pop 刪除列表某個元素
test.pop()
print("使用pop刪除列表最后一個元素 %s" % test)
結果:
使用pop刪除列表最后一個元素 ['b', 'c', 'd', 'e', ['e'], 'ab']
append() 方法和 extend() 方法都是向列表的末尾增加元素,它們的區別:
append() 方法是將參數作為一個元素增加到列表的末尾。
extend() 方法則是將參數作為一個列表去擴展列表的末尾。