タプルの要素存在確認を探索する
このステップでは、in
演算子を使用してタプル (tuple) 内に特定の要素が存在するかどうかを確認する方法を学びます。タプルは、要素の順序付けられた不変のシーケンスです。タプルを操作する際に、要素の存在を確認することは一般的な操作です。
まず、いくつかの要素を含む my_tuple
という名前のタプルを作成しましょう。
my_tuple = (1, 2, 3, 'a', 'b', 'c')
要素がタプル内に存在するかどうかを確認するには、in
演算子を使用できます。たとえば、数字 3
が my_tuple
に含まれているかどうかを確認するには、~/project
ディレクトリに tuple_membership.py
という名前の Python スクリプトを作成し、以下の内容を記述します。
my_tuple = (1, 2, 3, 'a', 'b', 'c')
if 3 in my_tuple:
print("3 is in my_tuple")
else:
print("3 is not in my_tuple")
ファイルを保存し、以下のコマンドを使用して実行します。
python ~/project/tuple_membership.py
以下の出力が表示されるはずです。
3 is in my_tuple
次に、タプル内に存在しない要素を確認してみましょう。tuple_membership.py
スクリプトを変更して、数字 4
が my_tuple
に含まれているかどうかを確認します。
my_tuple = (1, 2, 3, 'a', 'b', 'c')
if 4 in my_tuple:
print("4 is in my_tuple")
else:
print("4 is not in my_tuple")
ファイルを保存し、再度実行します。
python ~/project/tuple_membership.py
今回は、以下の出力が表示されます。
4 is not in my_tuple
また、タプル内の文字列の存在を確認することもできます。tuple_membership.py
スクリプトを変更して、文字列 'a'
が my_tuple
に含まれているかどうかを確認します。
my_tuple = (1, 2, 3, 'a', 'b', 'c')
if 'a' in my_tuple:
print("'a' is in my_tuple")
else:
print("'a' is not in my_tuple")
ファイルを保存して実行します。
python ~/project/tuple_membership.py
出力は以下のようになります。
'a' is in my_tuple
これで、in
演算子を使用してタプル内の要素の存在を効果的に確認する方法がわかりました。