タプル

基本

リストと同様に,タプルも複数の値・オブジェクトをまとめる.要素を,で区切って並べ,全体を( )で囲んで作成する.

t = (0, 1, 4, 9, 16, 25, 36, 49)
t
(0, 1, 4, 9, 16, 25, 36, 49)
type(t)
tuple

リストと同じように要素にアクセスできる.

t[0]
0
t[-1]
49
t[::-1]
(49, 36, 25, 16, 9, 4, 1, 0)

リストと同じように,タプルにある要素が含まれるかどうかチェックできる.

16 in t
True
16 not in t
False

タプルは不変(immutable)なオブジェクトであるため,タプルの要素は変更できない.

t[0] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-c8aeb8cd20ae> in <module>
----> 1 t[0] = 1

TypeError: 'tuple' object does not support item assignment

タプルに要素を追加することもできない.

t.append(64)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-46433dd8dfd1> in <module>
----> 1 t.append(64)

AttributeError: 'tuple' object has no attribute 'append'

パック・アンパック

タプルを作成するときの括弧は省略できる.

t = 2, 4, 6
t
(2, 4, 6)
type(t)
tuple

タプルの各要素の値を代入できる(「アンパック」と呼ばれる).

x, y, z = t
x
2
y
4
z
6

要素数が合っていないとアンパックできない.

x, y = t
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-757d34c4b6b9> in <module>
----> 1 x, y = t

ValueError: too many values to unpack (expected 2)
x, y, z, a = t
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-50f947a97b47> in <module>
----> 1 x, y, z, a = t

ValueError: not enough values to unpack (expected 4, got 3)

カンマ(,)で区切ることで,複数の変数に値をまとめて代入できるのは,右辺の複数の値がタプルにまとめられ(「パック」と呼ばれる),そのタプルの各要素が左辺でアンパックされて代入されることによる.

x, y, z = 1, 3, 5
x
1
y
3
z
5

ひとつのセルの中で複数の変数や値をカンマで区切って評価させ,コードセルの出力として確認できるのは,カンマで区切った値がタプルとしてパックされるからである.

x, y, z, 7
(1, 3, 5, 7)

一時変数を使うこと無く,以下のコードで変数の値の交換ができるのは,タプルのパックとアンパックによる動作である.

y, z, x = x, y, z
x, y, z
(5, 1, 3)

関数が複数の値を返すことができるのは,関数の戻り値がタプルに変換(パック)されるからである.

def fg(x):
    return x ** 2 - 2, 2 * x
r = fg(1)
r
(-1, 2)
type(r)
tuple
fx, gx = r
fx
-1
gx
2

リストから要素をアンパックすることもできる.

a = [0, 2, 4]
x, y, z = a
x
0
y
2
z
4

特殊なタプルの作成

1つの要素からなるタプルを作成するため,以下のコードを実行してもタプルにはならない.

t = (1)
t
1
type(t)
int

1つの要素からなるタプルを作成するには,末尾にカンマ,を付ける.

t = (1,)
t
(1,)

空のタプルはtuple関数を用いて作る.

t = tuple()
t
()

リストとタプルの相互変換

オブジェクトをリストからタプルに変換するには,tuple関数を呼び出す.

a = [1, 3, 5]
a
[1, 3, 5]
type(a)
list
b = tuple(a)
b
(1, 3, 5)
type(b)
tuple

オブジェクトをタプルからリストに変換するにはlist関数を呼び出す.

c = list(b)
c
[1, 3, 5]
type(c)
list