Python Tuple and Set

2026 資訊之芽 Python 語法班 簡報

2026 Mar. 15 講師 藍少君

Tuple

如何唸 Tuple ?

how to pronounce tuple center

https://mobile.twitter.com/gvanrossum/status/86144775731941376

Tuple

  • sequence:
    • 使用方法與 list 幾乎一致。
  • immutable:
    • 無法變更內部狀態。

Remark: string 也是一種 immutable sequence data type。

取得 Tuple

  • 標準寫法是用小括號 ( ) 將元素括起來,並以逗號分隔。
  • 可以在"沒有歧義"的情況下省略小括號。
  • 將多個值賦值給單個變數的行為,官方稱為 tuple packing。(實際行為是,將多個值打包成一個 tuple 進行賦值)
t1 = (1, "a")
t2 = (1, )
t3 = 1, "a"
t4 = 1,

Ambiguous Usage 1

  • c: list[tuple[int, str]]
  • i: list[int | str]
c = [(1, "a"), (1, "b")]
i = [1, "a", 1, "b"]

Ambiguous Usage 2

  • a: int
  • t: tuple[int]
a = (1)
t = (1,)

print(type(a)) # <class 'int'>
print(type(t)) # <class 'tuple'>

Sequence Unpacking

將一個 sequence 拆包,賦值給多個變數的語法。

基本用法:

a, b, c = [1, 2, 3] # a = 1, b = 2, c = 3
d, e = (1, "a")     # d = 1, e = 'a'
c1, c2 = "ab"       # c1 = 'a', c2 = 'b'

在基本用法中,左方變數數量要與 sequence 元素數量恰好一致,否則會產生 ValueError

Extended Sequence Unpacking

* 捕捉可變長度的剩餘元素:

a, b, *r = [1, 2, 3, 4, 5, 6]
# a = 1, b = 2, r = [3, 4, 5, 6]

a, b, *r = (1, 2, 3, 4, 5, 6)
# a = 1, b = 2, r = [3, 4, 5, 6]

a, *r, b = (1, 2, 3, 4, 5, 6)
# a = 1, r = [2, 3, 4, 5], b = 6

What is this ?

Python 如何解讀以下這段程式 ?

a, b, c, d = d, c, b, a
  1. 進行 tuple packing,將 d, c, b, a 打包成一個暫存 tuple。
  2. 進行 sequence unpacking,將 tuple 拆包賦值給 a, b, c, d

針對 a, b = b, a 這類太簡單的交換,Python 會用 SWAP 的方式進行,以優化效能。

Tuple 運算

  1. 加法 - 串接: (1, 2) + (3, 4) => (1, 2, 3, 4)
  2. 乘法 - 重複: (1, 2) * 3 => (1, 2, 1, 2, 1, 2)
  3. 比大小:
    • (1, 2) > (0, 5) => True
    • (1, "b") > (1, "a") => True
    • (1, 2, 3) > (1, 2) (若元素比完比不出來,最後比長度) => True

When to Use Tuples ?

一次性、結構化的傳遞、儲存某些資料。

舉例:

  • 表示一個向量、一個座標點: vec: tuple[int, int] = (x, y)
  • 表示一次實驗的數據: report: tuple[float, float] = (avg, std_dev)
  • 一個顏色數值: color: tuple[int, int, int] = (r, g, b)

通常這些資料的 順序 本身就有意義,我們不需要額外命名。或是這些資料是有關,但彼此獨立的,僅僅因一起被使用才形成結構。

Examples

coordinates = [(0, 1), (3, 2), (1, 7), (3, 7)]
coordinates.sort() # [(0, 1), (1, 7), (3, 2), (3, 7)]
data = [('Taipei', 30, 70), ('Taichung', 32, 10), ('Kaohsiung', 35, 30)]
for c, t, h in data:
    print(f"{c:{max(len(c_) for c_, *_ in data)}}: 攝氏 {t} 度,濕度 {h}%")
raw_scores = [("小明", (80, 60, 77)), ("大華", (78, 63, 55))]
weighted_averages = [(n, (c*3 + m*2 + p*1)/6) for n, (c, m, p) in raw_scores]

More Examples

map_ = { (1, 1): "wall", (1, 2): "wall", (1, 3): "wall",
         (2, 1): "wall", (3, 1): "door" }
symb = { "wall": '#', "door": ']', "free": '0' }

for y in range(4):
    for x in range(4):
        obj = map_.get((y, x), "free")
        print(f"{symb[obj]}", end=' ')
    print()

tuple 是 immutable 且 hashable,可以被當作 dictionary 的 key。

Much More Examples

def get_data_statistics(data: list[int]) -> tuple[int, int, float]:
    return max(data), min(data), sum(data)/len(data)
data = [1, 3, 7, 8, 9]
max_, _, avg = get_data_statistics(data)
print(f"Max: {max_}\nAvg: {avg}")

tuple 常常會和 function、class 的語法搭配出現,現在看不懂可以等教完 function、class 再回來看。

Pratical Examples

tuple usage 1 center
tuple usage 2 center

https://github.com/google-research/bert/blob/master/run_pretraining.py#L305
https://github.com/google-research/bert/blob/master/run_pretraining.py#L145

Set

Set

  • unordered collection with no duplicate elements
  • 就是數學學的那個集合。

set 是為 "效率" 而生 data type,初學不太會用到,認識他就好。

取得 Set

s1 = {1, 2, 3} # 用大括號表示 set
s2 = {} # 這會建立空 dictionary 不是空 set
s3 = set() # 這才會建立空 set
s4 = set([1, 3, 5])

Set 操作

s1 = {i for i in range(10)} # {0, 1, 2, ..., 9}
s2 = {i for i in range(0, 10, 2)} # {0, 2, 4, ..., 8}

s1 - s2 # {1, 3, 5, ..., 9}
s1 & s2 # {0, 2, 4, ..., 8}
s1 | s2 # {0, 1, 2, ..., 9}

Set 操作

s = set() # {}
s.add(3) # {3}
1 in s # False
3 in s # True

s.add(1) # {1, 3}
s.remove(1) # {3}
s.remove(2) # KeyError
s.discard(2) # NOP
s.discard(3) # {}
3 in s # False

References