Python中的元組資料型別


元組是另一種序列資料型別,它類似於列表。元組由多個逗號分隔的值組成。然而,與列表不同,元組用圓括號括起來。

示例

列表和元組之間的主要區別在於:列表用方括號 ( [ ] ) 括起來,其元素和大小都可以更改,而元組用圓括號 ( ( ) ) 括起來,並且不能更新。可以將元組視為只讀列表。例如 −

 實際演示

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

輸出

產生以下結果 −

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

以下程式碼對於元組無效,因為我們嘗試更新元組,這是不允許的。對於列表,也可能出現類似的情況 −

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

更新時間:2020 年 1 月 24 日

839 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告