1. ホーム 
  2. 備忘録 
  3. Python

タプル型

タプルについて

Python でリスト型のように複数の要素をまとめる方法としてタプル型が存在する

リスト型と異なる点は以下の通りである


  • l[0] = 'a'のように部分的な代入を認めていない
  • pop() や append() のような中身を追加・削除する関数が存在しない

初期化時に作成したタプルの構造を、基本的には変更することができないので、読み込み専用の値として取り扱うケースが多い


# タプルの宣言
a = (1, 2, 3)
b = 4, 5, 6
print(a, type(a))  # (1, 2, 3) <class 'tuple'>
print(b, type(b))  # (4, 5, 6) <class 'tuple'>

# 以下は型に注意すること
x = 7,
y = ()
z = (1)
print(x, type(x))  # (7,) <class 'tuple'>
print(y, type(y))  # () <class 'tuple'>
print(z, type(z))  # 1 <class 'int'>

タプルの書き換え

タプルの構造は基本的に変更することができないと書いたが、例外としてタプル同士の連結は行うことができる

タプル同士の連結は以下の方法でおこなう


### タプル同士の連結
t1 = (1, 2, 3)
t2 = (4, 5, 6)

# +演算子で連結する
# リスト型と同じくidが書き変わる
print(id(t1))   # 3019084431552
t1 = t1 + t2
print(t1)       # (1, 2, 3, 4, 5, 6)
print(id(t1))   # 3019083639296

t1 = (1, 2, 3)
t2 = (4, 5, 6)

# +=演算子で連結する
# リスト型と異なり、+=演算子でもidが書き変わることに注意
print(id(t1))   # 3019084431552
t1 += t2
print(t1)       # (1, 2, 3, 4, 5, 6)
print(id(t1))   # 3019083639296

また、他にもタプルの中にリストを持つ場合、リストの中身は書き換えることができる


### タプル内のリストの書き換え
t = ([1, 2, 3], [4, 5])

# 以下は先述のとおりエラーとなるが
t[0] = [10, 11]  # TypeError: 'tuple' object does not support item assignment

# タプル内のリストの値は書き換えられる
t[0][0] = 10
t[0][1] = 11
del t[0][2]
print(t)  # ([10, 11], [4, 5])


### タプル内のリストの連結について
l = [100, 101, 102]

# +演算子、+=演算子での連結方法はエラーとなるが
t[0] = t[0] + l     # TypeError: 'tuple' object does not support item assignment
t[0] += l       # TypeError: 'tuple' object does not support item assignment

# extend() であれば連結可能である
t[0].extend(l)
print(t)    # ([10, 11, 100, 101, 102], [4, 5])

タプルのアンパッキング

タプルのアンパッキングを使うと変数展開が楽になる

タプルのアンパッキングの例を以下に記載する


### タプルのアンパッキング
# タプルの変数から展開する
num_tuple = (1, 2)
x, y = num_tuple
print(x, y)         # 1 2

# 直接タプルから展開する
min, max = 0, 100
print(min, max)     # 0 100

# 変数の値の入れ替え
a, b = 'apple', 'orange'
print(a, b)     # apple orange
a, b = b, a
print(a, b)     # orange apple

タプルの使いどころ

タプルは先述のとおり、構造を容易に変更できない点を活かして読み込み専用の値として取り扱うケースが多い


### 選択肢の中から2個の果物を選ぶプログラムの場合
# 正しいプログラム
choose_from_two = ('apple', 'orange', 'grape', 'peach')
answer = []
answer.append('apple')
answer.append('peach')
print(choose_from_two)  # ('apple', 'orange', 'grape', 'peach')
print(answer)           # ['apple', 'peach']

# 誤ったプログラム
choose_from_two = ['apple', 'orange', 'grape', 'peach']
answer = []
# ここでプログラマが変数を間違えてしまうと...
choose_from_two.append('apple')
choose_from_two.append('peach')
print(choose_from_two)  # ['apple', 'orange', 'grape', 'peach', 'apple', 'peach']
print(answer)           # []

# 正しいプログラムのほうでは、変数を間違えたとしても
# choose_from_two に append することができないので
# エラーが発生して即座に間違いに気付くことができる