编写一个 Python 程序来移除或删除元组中的项。在此编程语言中,我们无法从元组中删除项。相反,我们必须将其分配给一个新元组。在此示例中,我们使用了元组切片和连接来移除元组项。第一个,numTuple[:3] + numTuple[4:] 移除了第三个元组项。
# Remove an Item from Tuple
numTuple = (9, 11, 22, 45, 67, 89, 15, 25, 19)
print("Tuple Items = ", numTuple)
numTuple = numTuple[:3] + numTuple[4:]
print("After Removing 4th Tuple Item = ", numTuple)
numTuple = numTuple[:5] + numTuple[7:]
print("After Removing 5th and 6th Tuple Item = ", numTuple)

Python 中的另一个选项是将元组转换为列表并使用 remove 函数,而不是移除列表项。接下来,程序将转换回元组。
numTuple = (2, 22, 33, 44, 5, 66, 77)
print("Tuple Items = ", numTuple)
numList = list(numTuple)
numList.remove(44)
numTuple1 = tuple(numList)
print("After Removing 3rd Tuple Item = ", numTuple1)
Tuple Items = (2, 22, 33, 44, 5, 66, 77)
After Removing 3rd Tuple Item = (2, 22, 33, 5, 66, 77)