- list.remove(obj) 移除列表中某个值的第一个匹配项
x=['one','two','three','four','five','six']
x.remove('three')
print(x)
'''
输出
['one', 'two', 'four', 'five', 'six']
'''
- list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
x=['one','two','three','four','five','six']
a=x.pop() #默认去除最后一个元素
print(a)
print(x)
b=x.pop(0) #去除第一个元素
print(b)
print(x)
c=x.pop(-2) #去除倒数第二个元素
print(c)
print(x)
'''
输出
six
['one', 'two', 'three', 'four', 'five']
one
['two', 'three', 'four', 'five']
four
['two', 'three', 'five']
'''
remove 和 pop 都可以删除元素,前者是指定具体要删除的元素,后者是指定一个索引
- 如果知道要删除的元素在列表中的位置,可使用del语句
x=['one','two','three','four','five','six']
del x[0:2]
print(x)
del x[1:2]
print(x)
'''
输出
['three', 'four', 'five', 'six']
['three', 'five', 'six']
'''
- 注:如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()。