
【Python 100日チャレンジ】Day 11 - タプルを扱う (tuple)
プログラミングの本質は、「データをどう扱うか」にあります。
アプリの設定、座標、色、誕生日など──
私たちの身のまわりには「変わってはいけないデータ」が意外とたくさんあります。
Pythonでは、そうしたデータを守るために
「タプル(tuple)」 という仕組みが用意されています。
一度作成したら変更できない、
いわば "凍結されたリスト" です❄️
タプルを使えば、
誤って値を上書きしてしまうようなミスを防げます。
安全で信頼性の高いプログラムづくりの第一歩。
今日は、そのタプルを一緒に学んでいきましょう😊
(15~20分で読了 ⭐⭐)
🎯 今日の学習目標
タプルとは何かを理解する
タプルとリストの違いを比較する
タプルの生成とアクセス方法
タプルの実践的な活用法
📚 事前知識
Day 7: リストを扱う(list) - リスト概念の理解
Day 9: 繰り返し文for - 繰り返し文の活用
🎯 学習目標 1: タプルとは何かを理解する
一言で説明
タプル = 変更できない(immutable) 順序のあるデータの集まり
リストのように複数の値を保存しますが、一度作成したら絶対に変更できません。
実生活の例え
リスト: ショッピングリスト(追加、削除、修正可能)
["りんご", "バナナ", "牛乳"]
→ "牛乳"の代わりに"ヨーグルト"に変更可能!
タプル: 誕生日(絶対に変更不可)
(1990, 5, 15)
→ 一度生まれた日付は変えられない!なぜタプルを使うのか?
1. データ保護
# リストは間違って変更される可能性あり
colors = ["赤", "青", "緑"]
colors[0] = "黒" # 変更される!
print(colors) # ['黒', '青', '緑']
# タプルは変更不可能 → 安全!
colors = ("赤", "青", "緑")
# colors[0] = "黒" # TypeError発生!2. パフォーマンス向上
タプルは、リストよりもメモリを少なく使用し、より速いです。
import sys
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3, 4, 5)
print(f"リストサイズ: {sys.getsizeof(list_data)} bytes")
print(f"タプルサイズ: {sys.getsizeof(tuple_data)} bytes")出力:
リストサイズ: 104 bytes
タプルサイズ: 80 bytes3. 辞書のキーとして使用可能
# リストは辞書のキーとして使用不可
# location = {[10, 20]: "東京"} # TypeError!
# タプルは辞書のキーとして使用可能
location = {(10, 20): "東京", (30, 40): "大阪"}
print(location[(10, 20)]) # 東京🎯 学習目標 2: タプルとリストの違いを比較する
リスト vs タプル比較
1. 変更可能性
リスト `[]`: ✅ 可能
タプル `()`: ❌ 不可能
2. 追加/削除
リスト `[]`: ✅ 可能
タプル `()`: ❌ 不可能
3. 速度
リスト `[]`: 普通
タプル `()`: 速い
4. メモリ
リスト `[]`: 多く使用
タプル `()`: 少なく使用
5. dict キー
リスト `[]`: ❌ 不可能
タプル `()`: ✅ 可能
6. 使用時期
リスト `[]`: 変更が必要なデータ
タプル `()`: 固定されたデータ
実践比較例
# リスト: ToDoリスト(追加/削除が頻繁)
todo_list = ["勉強する", "運動する", "読書する"]
todo_list.append("掃除する") # 追加可能
todo_list.remove("読書する") # 削除可能
print(todo_list) # ['勉強する', '運動する', '掃除する']
# タプル: 座標(一度決まったら変更なし)
position = (10, 20)
# position[0] = 30 # TypeError! 変更不可
print(f"位置: x={position[0]}, y={position[1]}")リストでのみ可能なこと
# リスト専用メソッド
my_list = [1, 2, 3]
my_list.append(4) # 追加
my_list.remove(2) # 削除
my_list[0] = 10 # 修正
my_list.sort() # ソート
my_list.reverse() # 逆順
# タプルではすべて不可能!
my_tuple = (1, 2, 3)
# my_tuple.append(4) # AttributeError!
# my_tuple.remove(2) # AttributeError!
# my_tuple[0] = 10 # TypeError!タプルとリストの共通機能
# どちらも可能なこと
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
# インデックス
print(my_list[0]) # 1
print(my_tuple[0]) # 1
# スライス
print(my_list[1:3]) # [2, 3]
print(my_tuple[1:3]) # (2, 3)
# len(), in, count(), index()
print(len(my_list)) # 5
print(3 in my_tuple) # True
print(my_list.count(3)) # 1
print(my_tuple.index(4)) # 3🎯 学習目標 3: タプルの生成とアクセス方法
タプルの生成
方法 1: 括弧を使用
# 基本形
fruits = ("りんご", "バナナ", "ぶどう")
print(fruits) # ('りんご', 'バナナ', 'ぶどう')
print(type(fruits)) # <class 'tuple'>方法 2: 括弧なし(カンマのみ)
# カンマだけでもタプル生成可能!
numbers = 1, 2, 3, 4, 5
print(numbers) # (1, 2, 3, 4, 5)
print(type(numbers)) # <class 'tuple'>方法 3: tuple() 関数使用
# リストをタプルに変換
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3, 4, 5)
# 文字列をタプルに変換
text = "Python"
char_tuple = tuple(text)
print(char_tuple) # ('P', 'y', 't', 'h', 'o', 'n')方法 4: 空タプルと単一要素タプル
# 空タプル
empty_tuple = ()
print(empty_tuple) # ()
print(len(empty_tuple)) # 0
# 単一要素タプル - カンマ必須!
single_tuple = (5,) # カンマが必要!
print(single_tuple) # (5,)
print(type(single_tuple)) # <class 'tuple'>
# カンマがないと普通の数値
not_tuple = (5)
print(type(not_tuple)) # <class 'int'>💡 重要
単一要素タプルは必ずカンマ(`,`)を付けなければなりません!
タプル要素へのアクセス
インデックス
colors = ("赤", "青", "緑", "黄", "紫")
# 正のインデックス
print(colors[0]) # 赤
print(colors[2]) # 緑
# 負のインデックス
print(colors[-1]) # 紫
print(colors[-2]) # 黄スライス
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(numbers[2:5]) # (2, 3, 4)
print(numbers[:3]) # (0, 1, 2)
print(numbers[7:]) # (7, 8, 9)
print(numbers[::2]) # (0, 2, 4, 6, 8) - 偶数のみ
print(numbers[::-1]) # (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) - 逆順タプルのアンパック(Unpacking)
タプルの最も強力な機能の一つ!
# 基本アンパック
point = (10, 20)
x, y = point
print(f"x: {x}, y: {y}") # x: 10, y: 20
# 複数の値を一度に
person = ("山田太郎", 25, "東京")
name, age, city = person
print(f"{name}さんは{age}歳、{city}在住")関数の戻り値として活用
def get_min_max(numbers):
"""最小値と最大値をタプルで返す"""
return (min(numbers), max(numbers))
numbers = [5, 2, 9, 1, 7]
min_val, max_val = get_min_max(numbers)
print(f"最小値: {min_val}, 最大値: {max_val}")出力:
最小値: 1, 最大値: 9* 演算子で残りを受け取る
# 最初と残り
numbers = (1, 2, 3, 4, 5)
first, *rest = numbers
print(f"最初: {first}") # 1
print(f"残り: {rest}") # [2, 3, 4, 5]
# 最初、最後、中間
first, *middle, last = numbers
print(f"最初: {first}, 中間: {middle}, 最後: {last}")
# 最初: 1, 中間: [2, 3, 4], 最後: 5タプルのメソッド
タプルは変更不可能なので、メソッドは2つだけです!
numbers = (1, 2, 3, 2, 4, 2, 5)
# count() - 特定の値の個数
print(numbers.count(2)) # 3
# index() - 特定の値の最初のインデックス
print(numbers.index(4)) # 4
print(numbers.index(2)) # 1 (最初の2の位置)🎯 学習目標 4: タプルの実践的な活用法
活用 1: 複数の値を同時に割り当て
# 変数の交換(swap)
a = 10
b = 20
# リストなしで簡単に!
a, b = b, a
print(f"a: {a}, b: {b}") # a: 20, b: 10活用 2: 関数で複数の値を返す
def calculate(a, b):
"""四則演算の結果をタプルで返す"""
return (a + b, a - b, a * b, a / b)
# 結果を一度に受け取る
add, sub, mul, div = calculate(10, 5)
print(f"足し算: {add}, 引き算: {sub}, 掛け算: {mul}, 割り算: {div}")出力:
足し算: 15, 引き算: 5, 掛け算: 50, 割り算: 2.0活用 3: 座標と位置の保存
# 2D座標
player_position = (100, 200)
enemy_position = (150, 180)
# 3D座標
cube_position = (10, 20, 30)
# RGB色
red = (255, 0, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
print(f"プレイヤー位置: x={player_position[0]}, y={player_position[1]}")
print(f"赤色RGB: {red}")活用 4: 定数グループの定義
# 曜日タプル(変更してはいけないデータ)
WEEKDAYS = ("月", "火", "水", "木", "金", "土", "日")
# 方向ベクトル
DIRECTIONS = {
"up": (0, -1),
"down": (0, 1),
"left": (-1, 0),
"right": (1, 0)
}
# 使用
today_index = 2
print(f"今日は{WEEKDAYS[today_index]}曜日") # 今日は水曜日
dx, dy = DIRECTIONS["right"]
print(f"右移動: ({dx}, {dy})")活用 5: 辞書のキーとして使用
# 座標をキーとして使うマップデータ
game_map = {
(0, 0): "スタート地点",
(1, 0): "木",
(2, 0): "敵",
(3, 0): "宝物",
(4, 0): "出口"
}
# 特定位置を確認
position = (2, 0)
print(f"{position}には{game_map[position]}があります。")活用 6: ループで複数の値を処理
# 学生情報(名前、年齢、点数)
students = [
("山田太郎", 20, 85),
("佐藤次郎", 22, 90),
("鈴木花子", 21, 95)
]
# アンパックしながら繰り返し
for name, age, score in students:
print(f"{name} ({age}歳): {score}点")出力:
山田太郎 (20歳): 85点
佐藤次郎 (22歳): 90点
鈴木花子 (21歳): 95点活用 7: enumerate()と一緒に使用
fruits = ["りんご", "バナナ", "ぶどう"]
# enumerate()は(インデックス, 値)タプルを返す
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")出力:
0: りんご
1: バナナ
2: ぶどう💻 実習例題
例題 1: 分数計算機
def add_fractions(frac1, frac2):
"""分数の足し算(タプルで分数を表現)"""
# frac1 = (分子, 分母), frac2 = (分子, 分母)
n1, d1 = frac1
n2, d2 = frac2
# 通分して計算
result_n = n1 * d2 + n2 * d1
result_d = d1 * d2
return (result_n, result_d)
# 1/2 + 1/3 計算
result = add_fractions((1, 2), (1, 3))
print(f"結果: {result[0]}/{result[1]}") # 結果: 5/6例題 2: 距離計算
import math
def distance(point1, point2):
"""2点間の距離計算"""
x1, y1 = point1
x2, y2 = point2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# 2点間の距離
p1 = (0, 0)
p2 = (3, 4)
dist = distance(p1, p2)
print(f"{p1}と{p2}の間の距離: {dist}") # 5.0例題 3: 成績処理システム
def process_scores(student_data):
"""学生成績処理(タプル活用)"""
results = []
for name, *scores in student_data:
total = sum(scores)
average = total / len(scores)
results.append((name, total, average))
return results
# 学生別科目点数
students = [
("山田太郎", 85, 90, 88),
("佐藤次郎", 92, 88, 95),
("鈴木花子", 78, 85, 80)
]
results = process_scores(students)
print("=== 成績結果 ===")
for name, total, avg in results:
print(f"{name}: 合計{total}, 平均{avg:.1f}")出力:
=== 成績結果 ===
山田太郎: 合計263, 平均87.7
佐藤次郎: 合計275, 平均91.7
鈴木花子: 合計243, 平均81.0💡 実践のコツと注意点
ポイント 1: 単一要素タプルはカンマ必須
# ❌ 間違った方法
not_tuple = (5)
print(type(not_tuple)) # <class 'int'>
# ✅ 正しい方法
is_tuple = (5,) # カンマ必須!
print(type(is_tuple)) # <class 'tuple'>ポイント 2: タプルは変更不可能だが連結は可能
# 既存のタプルは変更できないが
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# 連結して新しいタプルを生成することは可能!
combined = tuple1 + tuple2
print(combined) # (1, 2, 3, 4, 5, 6)
# 繰り返しも可能
repeated = tuple1 * 3
print(repeated) # (1, 2, 3, 1, 2, 3, 1, 2, 3)ポイント 3: タプル内のリストは変更可能
# タプル内にリストがあれば
mixed = (1, 2, [3, 4, 5])
# タプル自体は変更不可
# mixed[0] = 10 # TypeError!
# でも内部リストは変更可能!
mixed[2].append(6)
print(mixed) # (1, 2, [3, 4, 5, 6])ポイント 4: タプル vs リスト選択基準
# ✅ タプル使用
# - データが変更されてはいけない時
birth_date = (1990, 5, 15)
# - 関数の戻り値
def get_user_info():
return ("山田太郎", 25, "東京")
# - 辞書のキー
locations = {(10, 20): "東京"}
# ✅ リスト使用
# - データを追加/削除/修正する必要がある時
shopping_list = ["牛乳", "パン", "卵"]
shopping_list.append("果物")ポイント 5: アンパック時は個数一致必須
# ❌ 個数不一致
point = (10, 20, 30)
# x, y = point # ValueError! 3個を2個の変数に入れられない
# ✅ 個数一致
x, y, z = point
print(f"x: {x}, y: {y}, z: {z}")
# ✅ * 使用して残りを受け取る
first, *rest = point
print(f"最初: {first}, 残り: {rest}")ポイント 6: 括弧省略可能(でも明示する方が良い)
# 括弧なしでもタプル
coordinates = 10, 20
print(type(coordinates)) # <class 'tuple'>
# でも可読性のため括弧使用を推奨
coordinates = (10, 20) # より明確!🧪 練習問題
問題 1: 5人の学生の中で最高点と最低点を見つける
次の5人の学生リストがあります。
("山田太郎", 85)
("佐藤次郎", 92)
("鈴木花子", 78)
("田中三郎", 95)
("高橋四郎", 88)
この中で最も高い点数の学生と最も低い点数の学生を見つけて、それぞれの名前と点数を出力してください。
期待される出力:
最高点: 田中三郎 (95点)
最低点: 鈴木花子 (78点)💡 ヒント
各学生は(名前, 点数)形式のタプル
forループですべての学生を確認しながら最高点と最低点を追跡
`top_student[1]`で点数にアクセス可能
✅ 解答
def find_top_and_bottom(students):
"""最高点と最低点の学生を見つける"""
# 最初の学生で初期化
top_student = students[0]
bottom_student = students[0]
# すべての学生を確認
for student in students:
name, score = student # タプルをアンパック
# 最高点更新
if score > top_student[1]:
top_student = student
# 最低点更新
if score < bottom_student[1]:
bottom_student = student
return (top_student, bottom_student)
# テスト
students = [
("山田太郎", 85),
("佐藤次郎", 92),
("鈴木花子", 78),
("田中三郎", 95),
("高橋四郎", 88)
]
top, bottom = find_top_and_bottom(students)
print(f"最高点: {top[0]} ({top[1]}点)")
print(f"最低点: {bottom[0]} ({bottom[1]}点)")出力:
最高点: 田中三郎 (95点)
最低点: 鈴木花子 (78点)問題 2: ゲームキャラクターを移動させる
ゲームのプレイヤー位置が `(10, 20)` にいます。このプレイヤーを以下のように移動させてください:
上に1マス移動 → 方向 `(0, -1)` を適用
右に1マス移動 → 方向 `(1, 0)` を適用
左下に移動 → 方向 `(-1, 1)` を適用
各移動後の新しい位置を計算して出力してください。
期待される出力:
上移動: (10, 20) → (10, 19)
右移動: (10, 20) → (11, 20)
左下移動: (10, 20) → (9, 21)💡 ヒント
現在位置 `(x, y)` と移動方向 `(dx, dy)` を足す
新しい位置 = `(x + dx, y + dy)`
タプルのアンパックを使うと簡潔に書ける
✅ 解答
def move_position(current_pos, direction):
"""位置を移動する"""
x, y = current_pos
dx, dy = direction
new_x = x + dx
new_y = y + dy
return (new_x, new_y)
# テスト
player_pos = (10, 20)
# 上に移動 (y-1)
new_pos = move_position(player_pos, (0, -1))
print(f"上移動: {player_pos} → {new_pos}")
# 右に移動 (x+1)
new_pos = move_position(player_pos, (1, 0))
print(f"右移動: {player_pos} → {new_pos}")
# 左下に移動 (x-1, y+1)
new_pos = move_position(player_pos, (-1, 1))
print(f"左下移動: {player_pos} → {new_pos}")出力:
上移動: (10, 20) → (10, 19)
右移動: (10, 20) → (11, 20)
左下移動: (10, 20) → (9, 21)上移動: (10, 20) → (10, 19)
右移動: (10, 20) → (11, 20)
左下移動: (10, 20) → (9, 21)📝 今日学んだ内容のまとめ
タプルの定義:変更不可能な(immutable) 順序のあるデータの集まり
リストとの違い:タプルは変更不可、リストは変更可能
タプルの生成:`()`、カンマ、`tuple()` 関数使用
タプルのアンパック:複数の値を一度に変数に割り当て
活用:座標、色、関数の戻り値、辞書のキーなど
核心ポイント:
タプルは一度作成したら絶対に変更できません
単一要素タプルはカンマ必須: `(5,)`
リストより速くメモリ効率的
変更してはいけないデータにタプルを使用
🎯 実習課題
タプルを使って簡単な座標システムを作成してください:
プレイヤーの初期位置を(0, 0)として保存
移動コマンド(up/down/left/right)を受け取る
各コマンドに対応する方向ベクトルをタプルで定義
新しい位置を計算して出力
"quit"入力で終了
例:
DIRECTIONS = {
"up": (0, -1),
"down": (0, 1),
"left": (-1, 0),
"right": (1, 0)
}
position = (0, 0)
while True:
command = input("移動コマンド (up/down/left/right/quit): ")
if command == "quit":
print(f"最終位置: {position}")
break
if command in DIRECTIONS:
dx, dy = DIRECTIONS[command]
x, y = position
position = (x + dx, y + dy)
print(f"現在位置: {position}")
else:
print("無効なコマンドです")🔗 関連資料
📚 前回の学習
前回は、Phase 1の締めくくりとして数字当てゲームを作りました!
📚 次回の学習
次回は、キーと値のペアでデータを保存する辞書を学びます!
📚 シリーズをまとめて読む
Python 100日チャレンジの全記事は、
マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
よろしければ、フォローしていただけると嬉しいです!
🚀 遅いと思った時が一番早い時期です!🚀
Day 11/100 | Phase 2: データ型をマスター | #100DaysOfPython