在 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP