Tuple 元組

元組類似於清單，是任何類型的元素序列，但它們是不可變的，它們以括號表示。 
 
 符號用括號 
 內容不可變更 
 處理大量資料比 List 節省記憶體 
 讀取速度比串列(List)快 
 
 a = (1, 2, 3)
b = ('red', 'green', 'blue') 
 範例：利用 index 取值 
 t = (1, 2, 3 ,4 ,5)
print(t[0]) # 1
print(t[1]) # 2
print(t[2]) # 3 
 範例：如果函式一次回傳多個值時，這資料類型就是 Tuple。 
 def convert_seconds(seconds):
 hours = seconds // 3600
 minutes = (seconds - hours * 3600) // 60
 remaining_seconds = seconds - hours * 3600 - minutes * 60
 return hours, minutes, remaining_seconds
result = convert_seconds(5000)
type(result)

# Output: <class 'tuple'> 
 範例：Tuple 可以將多個不同值對應不同變數名 
 def convert_seconds(seconds):
 hours = seconds // 3600
 minutes = (seconds - hours * 3600) // 60
 remaining_seconds = seconds - hours * 3600 - minutes * 60
 return hours, minutes, remaining_seconds
result = convert_seconds(5000)
hours, minutes, seconds = result
print(hours, minutes, seconds)

# Output: 1 23 20 
 您可能會想，既然元組和清單類似，為什麼會有元組呢？當我們需要確保某個元素在某個位置且不會改變時，Tuples 就會很有用。由於 List(清單) 是可變的，因此元素的順序可以被改變。由於 Tuple(元組) 中元素的順序無法改變，元素在 Tuple(元組)中的位置就有了意義。一個很好的例子就是當一個函式回傳多個值時。在這種情況下，返回的是一個 Tuple(元組) 中的元素。返回值的順序很重要，而一個 Tuple(元組)可以確保順序不會改變。將 Tuple 的元素儲存於獨立的變數中，稱為 unpacking。這允許您從函數中取得多個回傳值，並將每個值儲存在自己的變數中。 
 範例：迭代於 List 與 Tuple 
 def full_emails(people):
 result = []
 for email, name in people:
 result.append("{} <{}>".format(name, email))
 return result
print(full_emails([("alex@example.com", "Alex Diego"), ("shay@example.com", "Shay Brandt")]))

# Output: ['Alex Diego <alex@example.com>', 'Shay Brandt <shay@example.com>']