Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách toán tử del làm việc trên tuple trong Python?


Không thể xóa từng phần tử riêng lẻ của tuple (vì immutable). Có thể tạo tuple mới loại bỏ phần tử không muốn bằng list comprehension hoặc slice. Để xóa hẳn toàn bộ tuple, dùng lệnh del.

Ví dụ

tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del(tup)
print("After deleting tup : ")
print(tup)

Kết quả: sau del tup, tuple không còn tồn tại, truy cập sẽ gây NameError.

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
  File "test.py", line 9, in 
    print tup;
NameError: name 'tup' is not defined

Lưu ý: del tup xóa biến tham chiếu, không phải "xóa phần tử". Để loại bỏ phần tử: new_tup = tup[:2] + tup[3:].