Python del 语句

2025年3月17日 | 阅读 3 分钟

引言

在 Python 中,`del` 关键字通常用于删除一个对象。由于 Python 中的一切都代表某种对象,因此 `del` 关键字也可用于删除列表、变量、列表的一部分等。`del` 语句不返回任何类型的值。

del 语句的语法

注意:`del` 是一个关键字,`obj_name` 可以是列表、字典、用户定义对象、变量等。

del 语句的示例

让我们看一些 del 语句的示例,并尝试删除一些项。

示例 1:在此程序中,我们将使用 del 语句删除一个变量

输出

35

Traceback (most recent call last):
  File "", line 10, in 
NameError: name 'c' is not defined
>

Python del Statement

示例 2:在此程序中,我们将使用 del 关键字删除一个列表和列表切片

输出

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
['a', 'b', 'c', 'd', 'e', 'f']
[0, 1, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 3, 4]
['a', 'c', 'd', 'e', 'f']

Traceback (most recent call last):
  File "", line 30, in 
NameError: name 'items_2' is not defined
>

Python del Statement

示例 3:在此程序中,我们将使用 del 语句删除字典和键值对

输出

{'up': 'down', 'forward': 'backward', 'small': 'down'}
{'short': 'long', 'you': 'me', 'Jack': 'John'}
{'forward': 'backward', 'small': 'down'}

Traceback (most recent call last):
   File "", line 18, in 
NameError: name 'dictionary_2' is not defined
>

Python del Statement

示例 4:删除用户定义的对象

输出

Name:  John wik
Age:  26
Address:  C-26, London
Phone No:  61562347
Traceback (most recent call last):
   File "", line 21, in 
NameError: name 'emp' is not defined
>

Python del Statement