Python del语句 --删除元素

对于列表,可以按照给定的索引来移除一个元素,或者移除切片或者清空整个列表;对于字典,可以按照给定的字典键来移除一个元素;可以删除整个变量,此后再引用该变量时会报错(直到另一个值被赋给它)

版本

python 3.8.9

字符串

del 不支持移除字符串项目(如 del str[0]),只能删除整个对象

set、tuple、int、float也只能删除整个对象

1
2
3
4
5
str_1 = '雨园'

del str_1 # 删除 str_1 变量
# 此后再引用 str_1 时会报错(直到另一个值被赋给它)
print(str_1)

输出

1
2
3
4
Traceback (most recent call last):
File "d:/开发/web/hexo/source/_posts/1.py", line 4, in <module>
print(str_1)
NameError: name 'str_1' is not defined

列表

支持移除列表的一个或多个元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
list_1 = ['a', 'b', 'c', 'd']

del list_1[0] # 移除第一个元素
print(list_1)

del list_1[:2] # 在前面移除的基础上再移除前两个元素
print(list_1)

del list_1[:] # 移除所有元素
print(list_1)

del list_1 # 删除 list_1 变量
# 此后再引用 list_1 时会报错(直到另一个值被赋给它)
print(list_1)

输出

1
2
3
4
5
6
7
['b', 'c', 'd']
['d']
[]
Traceback (most recent call last):
File "d:/开发/web/hexo/source/_posts/1.py", line 13, in <module>
print(list_1)
NameError: name 'list_1' is not defined

字典

1
2
3
4
5
6
7
8
9
10
11
dict_1 = {'a': 1, 'b': 2, 'c': 3}

del dict_1['a'] # 移除 'a' 键
print(dict_1)

del dict_1['b'], dict_1['c'] # 移除 'b' 'c' 键
print(dict_1)

del dict_1 # 删除 dict_1 变量
# 此后再引用 dict_1 时会报错(直到另一个值被赋给它)
print(dict_1)

输出

1
2
3
4
5
6
{'b': 2, 'c': 3}
{}
Traceback (most recent call last):
File "d:/开发/web/hexo/source/_posts/1.py", line 10, in <module>
print(dict_1)
NameError: name 'dict_1' is not defined