python 数组新增或删除元素

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() 方法则是将参数作为一个列表去扩展列表的末尾。

原文地址:https://www.cnblogs.com/APeng2019/p/10719406.html