タプルはPythonで提供されているデータ構造の一つ。タプルは固定長で変更できない複数の値の集合である。
タプルオブジェクト (tuple object) — Python 3.8.0 ドキュメント
タプルの生成は、変数にカンマで区切った値を代入する。
tup = 1,3,5 print(tup) print(type(tup)) # (1, 3, 5) # <class 'tuple'>
タプル内部にタプルを含むことも可能である。
tup = ((1,3,5), (2,4,6)) print(tup) # ((1, 3, 5), (2, 4, 6))
様々なデータをタプルに変換することが可能である。
生成したリストをタプルに変換してみる。
l = [10, 11, 12] print(l) print(type(l)) # [10, 11, 12] # <class 'list'> tup = tuple(l) print(tup) #(10, 11, 12)
文字列をタプルに変換してみる
tup = tuple('string')
print(tup)
# ('s', 't', 'r', 'i', 'n', 'g')
タプルの要素を取得するためには[]で要素番号を指定する。
tup = tuple('string')
print(tup[4])
# n
タプルでは足し算が利用できる。
tup = 1,3,5
tup = tup + ('abc', 'xyz') + (2,4,6)
print(tup)
# (1, 3, 5, 'abc', 'xyz', 2, 4, 6)
タプルでは掛け算も利用できる。
tup = 1,3,5 tup = tup * 5 print(tup) # (1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5)
タプルから値を取り出す操作をアンパックと呼ぶ。アンパックをするためには左辺にタプルの各要素を代入するための変数、右辺にアンパックしたいタプルを記述する。
tup = 1,3,5
a, b, c = tup
for i in a,b,c:
print(i)
#
1
3
5
ただし、左辺の変数の数はタプルの要素数と一致する必要があるので少々取り扱いが面倒くさい。
tup = 1,3,5
a, b = tup
for i in a,b,c:
print(i)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-18-d3bfa8403c9f> in <module>
1 tup = 1,3,5
----> 2 a, b = tup
3 for i in a,b,c:
4 print(i)
ValueError: too many values to unpack (expected 2)
タプルの長さがわからないときにはイテレーションですべての要素を順番に取得できる。
tup = 1,3,5,7
for a in tup:
print(a)
#
1
3
5
7
先頭の一部のタプルだけ利用したいときにはアンパックで*restを利用する。ただしrestはlist型であることに注意する
tup = 1,3,5,7,9 a, b, *rest = tup print(rest) type(rest) # [5, 7, 9] # list