タプルの基本(変更不可な配列)
タプル は ()(丸カッコ)で作る、変更不可なリストです。作成後は要素を追加・削除・変更できません。
1. タプルの作成と参照
point = (10, 20) # 2D座標
colors = ("赤", "青", "緑")
print(point[0])
print(colors[1])
print(len(colors))
▶ 出力結果
10 青 3
2. タプルは変更できない
point = (10, 20)
# point[0] = 99 # ❌ TypeError!変更できない
# ⭕ タプルをリストに変換してから変更
point_list = list(point)
point_list[0] = 99
point = tuple(point_list)
print(point)
▶ 出力結果
(99, 20)
3. 多重代入(アンパック)
# タプルの値を複数の変数に一度に代入
x, y = (100, 200)
print(f"x={x}, y={y}")
# 関数から複数の値を返す時によく使われる
name, age, city = ("田中", 25, "東京")
print(f"{name}({age}歳){city}在住")
▶ 出力結果
x=100, y=200 田中(25歳)東京在住
