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, indel tup[2:5] TypeError: 'tuple' object does not support item deletion
廣告