对于列表,可以按照给定的索引来移除一个元素,或者移除切片或者清空整个列表;对于字典,可以按照给定的字典键来移除一个元素;可以删除整个变量,此后再引用该变量时会报错(直到另一个值被赋给它)
版本
python 3.8.9
字符串
del 不支持移除字符串项目(如 del str[0]),只能删除整个对象
set、tuple、int、float也只能删除整个对象
1 2 3 4 5
| str_1 = '雨园'
del 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
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'] print(dict_1)
del dict_1['b'], dict_1['c'] print(dict_1)
del 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
|