Python 3 笔记 - 第3章 数据结构 - Tuple 元
2018-06-22 本文已影响7人
小叶与小茶
Tuple 也是使用比较频繁的一种序列类数据结构,元素写在圆扣号(“()”)里,用逗号相间隔。
虽然创建元组的时候,使用圆括号,但访问元素元素,仍然使用 “tuple[index]” 的形式。
1. Tuple 和 List 非常相似,最大的差异是,Tuple 中的元素不能改变。
# 列表中元素可以改变
super_box = [1, 2, 3, 4, 5]
super_box[0] = 5
print("super_box as a list : " + str(super_box))
# 元组中元素不能改变
super_box = (1, 2, 3, 4, 5)
super_box[0] = 5
print("super_box as a tuple : " + str(super_box))
执行结果为:
super_box as a list : [5, 2, 3, 4, 5]
super_box[0] = 5
TypeError: 'tuple' object does not support item assignment
2. 由于 Tuple 的元素不能改变,因此也不能删除其中某个元素,只能删除整个 Tuple。
# 删除元组中某个元素
super_box = (1, 2, 3, 4, 5)
del super_box[0]
print(super_box)
执行结果为:
del super_box[0]
TypeError: 'tuple' object doesn't support item deletion
由于 Tuple 和 List 非常类似,本章不再赘述