メインコンテンツへスキップ
Lesson1 / 5

タプルの基本 - 変更できないリスト

目次

1. このレッスンで学ぶこと

  • タプルとは何か
  • タプルの作成方法
  • リストとの違い
  • タプルの基本操作

2. タプルとは

タプルは、複数の値を順序付きで格納する、変更不可能(イミュータブル)なデータ構造です。

項目説明
書き方(要素1, 要素2, 要素3, ...)
変更不可能
順序あり
用途固定データ、座標、複数戻り値

主な特徴:

  • 丸括弧 () で囲んで作成する
  • 一度作成すると変更できない(要素の追加・削除・変更は不可)
  • インデックスでアクセスできる
  • リストより高速でメモリ効率が良い

簡単なコード例:

Python
# 基本的なタプル
fruits = ("りんご", "バナナ", "オレンジ")
print(fruits)  # ('りんご', 'バナナ', 'オレンジ')

# インデックスでアクセス
print(fruits[0])  # りんご

# 変更はできない
# fruits[0] = "ぶどう"  # エラー!

3. なぜタプルが必要なのか?

データを変更されたくない場合、タプルを使います。

Python
# リスト(変更可能)
colors_list = ["赤", "青", "黄"]
colors_list[0] = "緑"  # 変更できる
print(colors_list)

# タプル(変更不可)
colors_tuple = ("赤", "青", "黄")
# colors_tuple[0] = "緑"  # エラー!変更できない
print(colors_tuple)

実行結果:

['緑', '青', '黄']
('赤', '青', '黄')

タプルを使うことで、データを保護できます。

💡 豆知識: タプル(tuple)は「組」という意味です。数学では順序付きの値の組を表します。Pythonではイミュータブル(不変)なシーケンスとして実装されており、一度作成すると変更できません。


4. タプルの作成

基本的な作成方法

Python
# 丸括弧を使う
tuple1 = (1, 2, 3)
print(tuple1)

# カンマ区切り(括弧なし)
tuple2 = 1, 2, 3
print(tuple2)

# 空のタプル
empty = ()
print(f"空のタプル: {empty}")

# 1要素のタプル(カンマが必要!)
single = (1,)
print(f"1要素のタプル: {single}")
print(f"型: {type(single)}")

# カンマがないと
not_tuple = (1)
print(f"これはタプルではない: {not_tuple}")
print(f"型: {type(not_tuple)}")

実行結果:

(1, 2, 3)
(1, 2, 3)
空のタプル: ()
1要素のタプル: (1,)
型: <class 'tuple'>
これはタプルではない: 1
型: <class 'int'>

いろいろなタプル

Python
# 数値のタプル
numbers = (1, 2, 3, 4, 5)
print(f"数値: {numbers}")

# 文字列のタプル
fruits = ("りんご", "バナナ", "オレンジ")
print(f"文字列: {fruits}")

# 混合型のタプル
mixed = (1, "Python", 3.14, True)
print(f"混合型: {mixed}")

# ネストしたタプル
nested = ((1, 2), (3, 4), (5, 6))
print(f"ネスト: {nested}")

実行結果:

数値: (1, 2, 3, 4, 5)
文字列: ('りんご', 'バナナ', 'オレンジ')
混合型: (1, 'Python', 3.14, True)
ネスト: ((1, 2), (3, 4), (5, 6))

5. タプルの操作

要素へのアクセス

機能: インデックスを使って要素にアクセスします。

書き方:

Python
= タプル[インデックス]

用途: 特定位置の値取得、座標の成分取得

注意点:

  • インデックスは0から始まる
  • 負のインデックスも使える
  • 範囲外アクセスはエラー
Python
coordinates = (10, 20, 30)

# インデックスでアクセス
print(f"x座標: {coordinates[0]}")
print(f"y座標: {coordinates[1]}")
print(f"z座標: {coordinates[2]}")

# 負のインデックス
print(f"最後: {coordinates[-1]}")

実行結果:

x座標: 10
y座標: 20
z座標: 30
最後: 30

スライス

機能: タプルの一部を取り出します。

書き方:

Python
部分タプル = タプル[開始:終了]

用途: 範囲の取得、部分コピー

注意点: 新しいタプルが返される

Python
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# スライス
print(f"最初の3つ: {numbers[:3]}")
print(f"最後の3つ: {numbers[-3:]}")
print(f"2から5まで: {numbers[2:6]}")

実行結果:

最初の3つ: (0, 1, 2)
最後の3つ: (7, 8, 9)
2から5まで: (2, 3, 4, 5)

要素の検索

Python
fruits = ("りんご", "バナナ", "オレンジ", "バナナ")

# 存在チェック
print("バナナ" in fruits)
print("ぶどう" in fruits)

# インデックス取得
index = fruits.index("バナナ")
print(f"バナナの位置: {index}")

# 個数カウント
count = fruits.count("バナナ")
print(f"バナナの個数: {count}")

実行結果:

True
False
バナナの位置: 1
バナナの個数: 2

6. リストとの違い

変更可能性

Python
# リストは変更可能
my_list = [1, 2, 3]
my_list[0] = 10
print(f"リスト変更後: {my_list}")

# タプルは変更不可
my_tuple = (1, 2, 3)
try:
    my_tuple[0] = 10
except TypeError as e:
    print(f"タプルエラー: {e}")

実行結果:

リスト変更後: [10, 2, 3]
タプルエラー: 'tuple' object does not support item assignment

メモリとパフォーマンス

Python
import sys

# 同じ要素のリストとタプル
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)

# メモリサイズ
print(f"リストのサイズ: {sys.getsizeof(my_list)} bytes")
print(f"タプルのサイズ: {sys.getsizeof(my_tuple)} bytes")

実行結果:

リストのサイズ: 52 bytes
タプルのサイズ: 40 bytes

使えるメソッド

Python
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

# リストのメソッド
print("リストのメソッド:")
list_methods = [m for m in dir(my_list) if not m.startswith('_')]
print(list_methods[:5])

# タプルのメソッド
print("\nタプルのメソッド:")
tuple_methods = [m for m in dir(my_tuple) if not m.startswith('_')]
print(tuple_methods)

実行結果:

リストのメソッド:
['append', 'clear', 'copy', 'count', 'extend']

タプルのメソッド:
['count', 'index']

7. タプルのアンパック

基本的なアンパック

機能: タプルの要素を複数の変数に一度に代入します。

書き方:

Python
変数1, 変数2, ... = タプル

用途: 複数戻り値の受け取り、値の交換、座標の分解

注意点: 変数の数と要素数を合わせる

Python
# 座標のアンパック
point = (10, 20)
x, y = point
print(f"x = {x}, y = {y}")

# 複数の値を返す関数
def get_user_info():
    return "太郎", 25, "東京"

name, age, city = get_user_info()
print(f"名前: {name}, 年齢: {age}, 都市: {city}")

実行結果:

x = 10, y = 20
名前: 太郎, 年齢: 25, 都市: 東京

値の交換

Python
# 従来の方法(一時変数が必要)
a = 1
b = 2
temp = a
a = b
b = temp
print(f"a = {a}, b = {b}")

# タプルのアンパック(簡潔)
a = 1
b = 2
a, b = b, a
print(f"a = {a}, b = {b}")

実行結果:

a = 2, b = 1
a = 2, b = 1

アスタリスク付きアンパック

機能: 残りの要素をリストとして受け取ります。

書き方:

Python
変数1, *変数2, 変数3 = タプル

用途: 可変長の要素処理、最初と最後だけ取り出す

注意点: アスタリスクは1つだけ

Python
numbers = (1, 2, 3, 4, 5)

# 最初と残り
first, *rest = numbers
print(f"最初: {first}")
print(f"残り: {rest}")

# 最初、最後、中間
first, *middle, last = numbers
print(f"最初: {first}, 中間: {middle}, 最後: {last}")

実行結果:

最初: 1
残り: [2, 3, 4, 5]
最初: 1, 中間: [2, 3, 4], 最後: 5

8. 具体例

例1: 座標の管理

Python
# 2D座標
point_2d = (10, 20)
x, y = point_2d
print(f"2D座標: x={x}, y={y}")

# 3D座標
point_3d = (10, 20, 30)
x, y, z = point_3d
print(f"3D座標: x={x}, y={y}, z={z}")

# RGB色
color = (255, 128, 0)
r, g, b = color
print(f"RGB: R={r}, G={g}, B={b}")

実行結果:

2D座標: x=10, y=20
3D座標: x=10, y=20, z=30
RGB: R=255, G=128, B=0

例2: 関数の複数戻り値

Python
def calculate_stats(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return total, count, average

data = [85, 92, 78, 95, 88]
total, count, avg = calculate_stats(data)

print(f"合計: {total}")
print(f"個数: {count}")
print(f"平均: {avg:.2f}")

実行結果:

合計: 438
個数: 5
平均: 87.60

例3: 日付と時刻

Python
# 日付(年、月、日)
date = (2024, 12, 6)
year, month, day = date
print(f"日付: {year}{month}{day}日")

# 時刻(時、分、秒)
time = (14, 30, 45)
hour, minute, second = time
print(f"時刻: {hour}:{minute:02d}:{second:02d}")

実行結果:

日付: 2024年12月6日
時刻: 14:30:45

9. 練習問題

問題1(基礎)⭐☆☆

座標 (5, 10) をアンパックしてx, yに代入してください。

💡 ヒント

x, y = タプル の形式を使います。

✅ 解答例
Python
point = (5, 10)
x, y = point
print(f"x = {x}, y = {y}")

実行結果:

x = 5, y = 10

問題2(基礎)⭐☆☆

タプル (1, 2, 3, 4, 5) の最初と最後の要素を表示してください。

💡 ヒント

インデックス0と-1を使います。

✅ 解答例
Python
numbers = (1, 2, 3, 4, 5)
print(f"最初: {numbers[0]}")
print(f"最後: {numbers[-1]}")

実行結果:

最初: 1
最後: 5

問題3(応用)⭐⭐☆

2つの変数a=1, b=2の値をタプルのアンパックを使って交換してください。

💡 ヒント

a, b = b, a を使います。

✅ 解答例
Python
a = 1
b = 2
print(f"交換前: a={a}, b={b}")

a, b = b, a
print(f"交換後: a={a}, b={b}")

実行結果:

交換前: a=1, b=2
交換後: a=2, b=1

10. まとめ

このレッスンでは、タプルの基本概念と使い方を学びました。

  • タプルは変更しないデータを扱うための基本データ型です。
  • 丸括弧で要素をまとめ、インデックスで参照できます。
  • リストとの違い(イミュータブル)を理解して使い分けられます。
  • 複数値の返却や固定設定値の管理に適していることを確認しました。
  • 変更不要なデータを明示することで、意図が伝わるコードになります。