python 提供了四种剔除列表中数据的方法,分别是 del、pop、remove 和 clear。

1. del

删除整个列表 或 删除指定下标的元素

example_list = ['apple', 'banana', 'orange']

# 删除整个列表
del example_list   # 也可以写作 del(example_list)
print(example_lists)   # 此时打印会抛出异常 NameError: name 'example_list' is not defined

# 删除指定下标的元素
del example_list[0]
print(example_list)   # 返回值 ['banana', 'orange']

2. pop

删除列表中指定下标的元素,默认删除最后一个,并返回被删除的元素

example_list = ['apple', 'banana', 'orange']

# 指定要删除元素的下标
pop_list = example_list.pop(0)
print(pop_list )  # 返回值 :'apple'
print(example_list)  # 返回值: ['banana', 'orange']

3. remove

删除列表中的指定元素,如果找不到会抛出异常

example_list = ['apple', 'banana', 'orange']

# 删除指定元素
example_list.remove('apple')
print(example_list )   # 返回值: ['banana', 'orange']

4. clear

清空列表中所有元素

example_list = ['apple', 'banana', 'orange']

# 清空列表中元素
example_list .clear()
print(example_list )   # 返回值: [ ]