tuple 元组变数

Python 基础: tuple 元组变数

list 串列 功能一样,但资料不能被修改

List 串列与 Tuple 元组差异

差异 List 串列 Tuple 元组
内容 内容可改变,新增与删除 内容不可异动
执行速度 较慢 较快
安全 较低 较高,因为资料不会被异动

一般 tuple 元组

tuple_1 = (1, 2, 3, 4, 5)
print("tuple_1: ", tuple_1)
print("tuple_1[3]: ", tuple_1[3])
# tuple_1:  (1, 2, 3, 4, 5)
# tuple_1[3]:  4
tuple_1 = (1, "KJ", True)
print("tuple_1: ", tuple_1)
# tuple_1:  (1, 'KJ', True)

重複 tuple 元组

tuple_1 = (1, 2, 3)
tuple_2 = tuple_1 * 2
print("tuple_1: ", tuple_1)
print("tuple_2: ", tuple_2)

# tuple_1:  (1, 2, 3)
# tuple_2:  (1, 2, 3, 1, 2, 3)

取得 tuple 元组中间元素

tuple_1 = (1, 2, 3, 4, 5, 6, 7)
tuple_2 = tuple_1[2:5]
print("tuple_1: ", tuple_1)
print("tuple_2: ", tuple_2)

# tuple_1:  (1, 2, 3, 4, 5, 6, 7)
# tuple_2:  (3, 4, 5)

错误案例

无法修改

TypeError: ’tuple’ object does not support item assignment

tuple_1 = (1, 2, 3, 4, 5, 6, 7)
tuple_1[3] = 33

# TypeError: 'tuple' object does not support item assignment

无法删除

TypeError: ’tuple’ object does not support item deletion

tuple_1 = (1, 2, 3, 4, 5, 6, 7)
del tuple_1[2:5]

# TypeError: 'tuple' object does not support item deletion

参考资料