文字列タプルについて学ぶ
このステップでは、Python の文字列タプルについて学びます。タプルは、要素の順序付けられた不変(変更できない)シーケンスです。タプルはリストに似ていますが、角括弧 []
ではなく丸括弧 ()
を使って定義されます。文字列タプルは、各要素が文字列であるタプルです。Python でデータのコレクションを扱うには、タプルを理解することが重要です。
まずは簡単な文字列タプルを作成してみましょう。LabEx 環境の VS Code エディタを開きます。~/project
ディレクトリに string_tuple.py
という名前の新しいファイルを作成します。
## Create a string tuple
my_tuple = ("apple", "banana", "cherry")
## Print the tuple
print(my_tuple)
ファイルを保存し、ターミナルで以下のコマンドを使ってスクリプトを実行します。
python ~/project/string_tuple.py
以下の出力が表示されるはずです。
('apple', 'banana', 'cherry')
では、文字列タプルに関するいくつかの一般的な操作を探索してみましょう。
- 要素へのアクセス:リストと同じように、インデックスを使ってタプルの要素にアクセスすることができます。
my_tuple = ("apple", "banana", "cherry")
## Access the first element
first_element = my_tuple[0]
print(first_element)
## Access the second element
second_element = my_tuple[1]
print(second_element)
string_tuple.py
に変更を保存し、スクリプトを再度実行します。
python ~/project/string_tuple.py
出力は以下のようになるはずです。
apple
banana
- タプルの長さ:
len()
関数を使って、タプルの要素数を求めることができます。
my_tuple = ("apple", "banana", "cherry")
## Get the length of the tuple
tuple_length = len(my_tuple)
print(tuple_length)
string_tuple.py
に変更を保存し、スクリプトを実行します。
python ~/project/string_tuple.py
出力は以下のようになるはずです。
3
- 不変性:タプルは不変であり、作成後に要素を変更することはできません。タプルを変更しようとすると、エラーが発生します。
my_tuple = ("apple", "banana", "cherry")
## Try to modify the tuple (this will raise an error)
## my_tuple[0] = "grape" ## This line will cause an error
my_tuple[0] = "grape"
の行のコメントを外すと、TypeError
が発生します。エラーを確認するために試してみることができますが、エラーが発生するとスクリプトの実行が停止するため、その後は再度コメントアウトしておいてください。
- タプルの連結:
+
演算子を使って、2 つのタプルを連結することができます。
tuple1 = ("apple", "banana")
tuple2 = ("cherry", "date")
## Concatenate the tuples
combined_tuple = tuple1 + tuple2
print(combined_tuple)
string_tuple.py
に変更を保存し、スクリプトを実行します。
python ~/project/string_tuple.py
出力は以下のようになるはずです。
('apple', 'banana', 'cherry', 'date')
これらの基本的な操作を理解することで、Python で文字列タプルを効果的に扱うことができるようになります。