タプル (tuple)
不変なデータを格納した順序付きデータ構造。添え字は 0
から始まる。異なる種類のデータを無作為に含む。
参考:
タプル型 (tuple) | Python 3.x ドキュメント [公式]
使い方
タプルを作成する。
assort = (1, 2, 3, "Hello", "John", "Bye")
空のタプルを作成する。
empty = ()
要素が一つだけのタプルを作成する場合は、一つの要素の後にコンマを付ける。
one = ("Earth",)
入れ子のタプルを作成する。
container = ("Blue", "Red", ("Black", "White"), "Yellow")
参考:
Python でタプルの要素を追加・変更・削除 | note.nkmk.me
要素数/長さを取得する (len)
len
関数を使ってタプルの長さを取得する。
greetings = ("Hello", "Hi", "Hey", "Welcome", "Bye") print(len(greetings))
参考:
タプルの長さ (要素数) を取得する | Let’s プログラミング
Tuple len() Method | Tutorials Point
要素の位置を探す (index)
参考:
Python のリストの要素のインデックス (何番目か) を取得 | note.nkmk.me
ジェネレータ式
参考:
Python の tuple 内包表記の落とし穴 | done is better than perfect
Additional Unpacking Generalizations (PEP 448) | Python.org [Official]
Why is there no tuple comprehension in Python? – Stack Overflow
インデックスエラー
参考:
Python で tuple index out of range というエラーが出る – スタック・オーバーフロー
内包表記
タプルでは内包表記は使用できない。代わりとしては、ジェネレータ式を使用する。
参考:
タプル内包表記とジェネレータ内容表記!タプルには内包表記はありません! | kamotora
Tuple Comprehension in Python is it Possible? | Python Pool
Why is there no tuple comprehension in Python? – Stack Overflow
ハッシュ
タプルは不変 (immutable) なデータ型でありハッシュ可能 (hashable) であるため、辞書のキーとして用いることができる。
参考:
hash 関数の使い方と注意点を実例で解説/タプル (tuple) とは何か? | Proぐらし
まとめ
参考: