1.定義:元組和列表類似,但是元組的元素不可變,元組一旦創建,用任何方法都不可以修改其元素。
元組的定義方式和列表相同,但元組在定義是所有元素都放在一對圓括號”(“和”)“中,而不是方括號中。下面是合法的元組:
(10,20,30,40) (‘abcd’,’efgh’,’python’)
2.創建元祖
使用”=“將一個元組賦值給變量。
>>>a_tuple=('a','b','python','z','example')
>>>a_tuple
('a','b','python','z','example')
3.讀取元素
用變量名加元素序號(放中括號中)即可訪問元組中某個元素。與列表相同,元組中的元素也有都有固定的順序,第一個元素的序號爲0,元組元素序號的規定與列表相同。
>>>a_tuple[2]
'python'
>>>a_tuple[-1]
'example'
>>>a_tuple[-5]
'a'
>>>a_tuple[-7]
Traceback (most recent call last):
File "<pyshell#68>" , line 1, in <module>
a_tuple[-7]
IndexError: tuple index out of range
4.元組切片
與列表一樣,元組也可以進行切片操作。對列表切片可以得到新的列表,對元組切片可以得到新的元組。
>>>a_tuple[1:3]
('b','python')
4.檢索元素
(1)使用count()方法計算元組中某個元素出現的次數。
>>>a_tuple.count('b')
1
(2)使用in運算符返回某個元素是否在該元組中。
>>>'ab' in a_tuple
False
>>>'z' in a_tuple
True
(3)使用index()方法返回某個元素在元組中的準確位置。
>>>a_tuple.index('z')
3
>>>a_tuple.index(5)
Traceback (most recent call last):
File "<pyshell#78>" , line 1, in <module>
a_tuple.index(5)
ValueError: tuple.index(x): x not in tuple
5.元組同時賦多個值
可以利用元組來一次性地對多個變量賦值。
>>>v_tuple=(False,3.5,'exp')
>>>(x,y,z)=v_tuple
>>>x
False
>>>y
3.5
>>>z
'exp'