Python中的del运算符如何作用于元组?


一个元组是由逗号分隔的Python对象的排序且不可变的集合。与列表类似,元组也是序列。元组与列表的不同之处在于,元组不能修改,而列表可以修改,并且元组使用圆括号而不是方括号。

tup=('tutorials', 'point', 2022,True) print(tup)

如果执行上述代码片段,则会产生以下输出:

('tutorials', 'point', 2022, True)

在本文中,我们将讨论在元组上使用del运算符。

del运算符

del关键字主要用于Python中删除对象。因为Python中的一切都是对象,所以del关键字可以用来删除元组、切片元组、删除字典、从字典中删除键值对、删除变量等等。

语法

del object_name

元组中的del运算符用于删除整个元组。由于元组是不可变的,因此无法删除元组中的特定元素。

示例1

在下面的示例中,我们使用del运算符显式删除整个元组。

tup=('tutorials', 'point', 2022,True) print(tup) del(tup) print("After deleting the tuple:") print(tup)

输出

在下面的输出中,您可以看到del运算符已经删除了整个元组,当我们想要打印删除整个元组后的元组时,会弹出错误。

('tutorials', 'point', 2022, True)
After deleting the tuple:
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(tup)
NameError: name 'tup' is not defined

在列表中,我们使用del运算符删除列表的一部分。由于元组是不可变的,因此我们不能删除元组的切片。

示例2

tup = ("Tutorialspoint", "is", "the", "best", "platform", "to", "learn", "new", "skills") print("The below part of the tuple needs to be deleted") print(tup[2:5]) del tup[2:5] print("After deleting:") print(tup)

输出

上述代码的输出如下:

The below part of the tuple needs to be deleted
('the', 'best', 'platform')
Traceback (most recent call last):
  File "main.py", line 4, in 
del tup[2:5]
TypeError: 'tuple' object does not support item deletion

更新于:2023年11月2日

6K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.