Tuple là immutable object. Không thể modify (append/insert). Workaround:
- Chuyển tuple → list bằng
list() - Append/insert vào list
- Chuyển lại tuple bằng
tuple()
Ví dụ
>>> T1 = (10, 50, 20, 9, 40, 25, 60, 30, 1, 56) >>> L1 = list(T1) >>> L1 [10, 50, 20, 9, 40, 25, 60, 30, 1, 56] >>> L1.append(100) >>> L1.insert(4, 45) >>> T1 = tuple(L1) >>> T1 (10, 50, 20, 9, 45, 40, 25, 60, 30, 1, 56, 100)
Lưu ý: Tạo tuple mới, tuple cũ không đổi. Phù hợp khi ít modify. Cần modify thường → dùng list.