元祖的介绍
python的元祖与列表类似,不同之处在于元祖的元素不能修改.
元祖使用小括号,列表使用方括号
元祖的关键字:tuple (塔泡)
a_tuple = (1, 3, 5, 9)
print(a_tuple[0])
print(a_tuple[1])
print(a_tuple[2])
print(a_tuple[3])
修改(错误演示):
a_tuple = (1, 3, 5, 9)
a_tuple[1] = '哈哈哈'
当我们对元祖进行修改时,会触发 TypeError: ‘tuple’ object does not support item assignment 的错误,这说明元祖的内容不可修改,包括不能删除其中的元素
访问元组里的元素的时候,可以通过下标获取,而且,我们可以通过下标获取多个元素组成的元组
tu = (1,2,67,89,90,45)
print(tu[2:4:])
元祖相加(连接组合)
t1 =(1,2,3)
t2 =(4,5,6)
t3 = t1+ t2
print(t3)
元祖的遍历
t1 = (1, 2, 3)
for x in t1:
print(x)
元祖中的内置函数
index,count 两者的用法与字符串和列表中的用法相同
a = ('a', 'b', 'c', 'a', 'b')
print(a.index('a', 1, 4))
print(a.count('b'))
错误演示:
a = ('a', 'b', 'c', 'a', 'b')
print(a.index('a', 1, 3))
此时触发 ValueError: tuple.index(x): x not in tuple 错误,意思是索引的值不在元祖中,这是因为1-2的区间内没有’a’