Pythonで要素が1個のタプルには末尾にカンマが必要
Modified: | Tags: Python
Pythonのイミュータブル(変更不可)なシーケンスオブジェクトであるタプル。要素数が1個のタプルや空のタプルを生成するときは注意が必要。
要素数が1個のタプル
要素数が1個のタプルを生成しようとして丸括弧()
の中に1つだけ要素を書くと、丸括弧()
は無視されて、タプルとは見なされない。
single_tuple_error = (10)
print(single_tuple_error)
# 10
print(type(single_tuple_error))
# <class 'int'>
source: tuple_single_empty.py
要素数が1個のタプルを生成する場合は、末尾にカンマ,
が必要。
single_tuple = (10, )
print(single_tuple)
# (10,)
print(type(single_tuple))
# <class 'tuple'>
source: tuple_single_empty.py
要素数が1個でもタプルはタプルなので、要素を取り出すにはインデックス[]
で指定すればよい。
print(single_tuple[0])
# 10
source: tuple_single_empty.py
例えば、+
演算子で複数のタプルを連結する場合、要素を1個追加しようとして,
を忘れるとエラーになるので注意。
# print((0, 1, 2) + (3))
# TypeError: can only concatenate tuple (not "int") to tuple
print((0, 1, 2) + (3, ))
# (0, 1, 2, 3)
source: tuple_single_empty.py
タプルの丸括弧は省略可能
なぜ要素が1個のタプルにカンマ,
が必要かというと、「タプルは丸括弧()
に囲まれた値」ではなく「カンマ,
で区切られた値」だから。
タプルを作るのはカンマであり、丸括弧ではありません。
組み込み型 - タプル型 (tuple) — Python 3.11.3 ドキュメント
丸括弧()
が省略されていてもタプルとして扱われる。
t = 0, 1, 2
print(t)
# (0, 1, 2)
print(type(t))
# <class 'tuple'>
source: tuple_single_empty.py
末尾に不要なカンマ,
があるとタプルと見なされてしまうので注意。
t = 0,
print(t)
# (0,)
print(type(t))
# <class 'tuple'>
source: tuple_single_empty.py
空のタプル
上述のようにタプルを表すときの丸括弧()
は省略可能だが、空のタプルを生成する場合は必須。
空白やカンマ,
だけだとエラー(SyntaxError
)になる。
empty_tuple = ()
print(empty_tuple)
# ()
print(type(empty_tuple))
# <class 'tuple'>
# empty_tuple_error =
# SyntaxError: invalid syntax
# empty_tuple_error = ,
# SyntaxError: invalid syntax
# empty_tuple_error = (,)
# SyntaxError: invalid syntax
source: tuple_single_empty.py
空のタプルは引数なしのtuple()
でも生成可能。
empty_tuple = tuple()
print(empty_tuple)
# ()
print(type(empty_tuple))
# <class 'tuple'>
source: tuple_single_empty.py
関数の引数でのタプル
構文上の曖昧さがある場合もタプルの丸括弧()
が必須。
関数の引数はカンマ,
で区切って指定するが、この場合は丸括弧()
の有無でタプルかどうかを明示的に表す必要がある。
丸括弧()
が無いとそれぞれの値がそれぞれの引数に渡され、丸括弧()
で囲むとタプルとして一つの引数に渡される。
def example(a, b):
print(a, type(a))
print(b, type(b))
example(0, 1)
# 0 <class 'int'>
# 1 <class 'int'>
# example((0, 1))
# TypeError: example() missing 1 required positional argument: 'b'
example((0, 1), 2)
# (0, 1) <class 'tuple'>
# 2 <class 'int'>
source: tuple_single_empty.py
タプルに*
を付けると、タプルの要素を展開して引数に渡すこともできる。
example(*(0, 1))
# 0 <class 'int'>
# 1 <class 'int'>
source: tuple_single_empty.py