增
append 尾部追加元素
lst = ['a', 'b', 'c']
lst.append('d')
print(lst) # ['a', 'b', 'c', 'd']
insert 任意位置插入元素
lst = ['a', 'b', 'c']
lst.insert(0, 'x')
lst.insert(len(lst), 'y')
print(lst) # ['x', 'a', 'b', 'c', 'y']
extend 将一个列表合并到另一个列表尾部
lst = ['a', 'b', 'c']
ext = ['d', 'e', 'f']
lst.extend(ext)
print(lst)
删
del 彻底删除元素
注意, del后不加列表下标时, 将清楚整个列表, 包括变量栈空间也会被移除
lst = ['a', 'b', 'c']
del lst[0]
print(lst) # ['b', 'c']
pop 弹出列表元素, 默认尾部弹出
pop 不加索引时, 默认弹出列表尾部元素, 加索引时, 弹出指定元素
lst = ['a', 'b', 'c', 'd']
lst.pop()
print(lst) # ['a', 'b', 'c']
lst.pop(1)
print(lst) # ['a', 'c']
remove 根据元素值移除元素
remove 每次只移除一个元素, 当有多个相同元素时, 移除相同元素中的第一个
lst = ['a', 'b', 'c', 'b', 'd']
lst.remove('b')
print(lst) # ['a', 'c', 'b', 'd']
改
通过下标修改
lst = ['a', 'b', 'c', 'b', 'd']
lst[3] = 'x'
print(lst) # ['a', 'b', 'c', 'x', 'd']
查
in, not in 元素是否存在于列表中
lst = ['a', 'b', 'c', 'b', 'd']
print('a' in lst) # True
print('a' not in lst) # False
index 元素是否存在与列表中, 不存在报异常
lst = ['a', 'b', 'c', 'b', 'd']
print(lst.index('b')) # 1
print(lst.index('x')) # ValueError: 'x' is not in list
count 元素在列表中的个数
lst = ['a', 'b', 'c', 'b', 'd']
print(lst.count('b')) # 2
排序
sort 列表排序
lst = ['a', 'b', 'c', 'b', 'd']
lst.sort(reverse = True)
print(lst) # ['d', 'c', 'b', 'b', 'a']
lst.sort()
print(lst) # ['a', 'b', 'b', 'c', 'd']