Python Tuple (元組)

Tuple 和 List 很相似,都是有序的元素集合,主要差別是 Tuple 是不可變的 (immutable),一旦建立就不能修改。

建立 Tuple

使用小括號 () 建立 Tuple:

# 空的 tuple
empty_tuple = ()

# 有元素的 tuple
fruits = ("apple", "banana", "orange")
numbers = (1, 2, 3, 4, 5)

# 也可以省略小括號
colors = "red", "green", "blue"
print(type(colors))  # <class 'tuple'>

建立只有一個元素的 tuple 時,必須加上逗號:

# 這是 tuple
single = (1,)
print(type(single))  # <class 'tuple'>

這是整數,不是 tuple

not_tuple = (1) print(type(not_tuple)) # <class 'int'>

存取元素

和 List 一樣使用索引存取:

fruits = ("apple", "banana", "orange")

print(fruits[0])   # apple
print(fruits[-1])  # orange
print(fruits[1:])  # ('banana', 'orange')

Tuple 是不可變的

一旦建立 Tuple,就不能修改它的內容:

fruits = ("apple", "banana", "orange")

# 不能修改元素
# fruits[0] = "grape"  # TypeError!

# 不能新增元素
# fruits.append("grape")  # AttributeError!

# 不能刪除元素
# del fruits[0]  # TypeError!

如果需要「修改」Tuple,只能建立一個新的:

fruits = ("apple", "banana", "orange")
fruits = fruits + ("grape",)
print(fruits)  # ('apple', 'banana', 'orange', 'grape')

Tuple 長度

fruits = ("apple", "banana", "orange")
print(len(fruits))  # 3

遍歷 Tuple

fruits = ("apple", "banana", "orange")

for fruit in fruits:
    print(fruit)

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

檢查元素是否存在

fruits = ("apple", "banana", "orange")

print("apple" in fruits)      # True
print("grape" in fruits)      # False
print("grape" not in fruits)  # True

Tuple 方法

因為 Tuple 是不可變的,只有兩個方法:

fruits = ("apple", "banana", "orange", "banana")

print(fruits.count("banana"))  # 2(banana 出現的次數)
print(fruits.index("orange"))  # 2(orange 第一次出現的索引)

Tuple Unpacking

可以將 Tuple 的元素分別指定給變數:

# 基本 unpacking
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x)  # 10
print(y)  # 20
print(z)  # 30

# 交換變數(其實也是 tuple unpacking)
a, b = 1, 2
a, b = b, a
print(a, b)  # 2 1

# 使用 * 收集剩餘元素
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

什麼時候用 Tuple?

Tuple 相比 List:

  1. 保護資料不被修改:當你不希望資料被意外修改時
  2. 效能較好:Tuple 比 List 佔用更少的記憶體,存取速度也稍快
  3. 可以作為 dict 的 key:因為 Tuple 是不可變的,可以作為字典的 key
  4. 函數回傳多個值:函數回傳多個值時,其實是回傳 Tuple
# 函數回傳多個值
def get_name_and_age():
    return "Alice", 25  # 回傳 tuple

name, age = get_name_and_age()
print(name)  # Alice
print(age)   # 25

# Tuple 可以作為 dict 的 key
locations = {
    (0, 0): "origin",
    (1, 2): "point A"
}
print(locations[(0, 0)])  # origin

Tuple 和 List 轉換

# List 轉 Tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # (1, 2, 3)

# Tuple 轉 List
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)  # [1, 2, 3]