2025.10.18(更新日: 2025.10.18)
【Python】indexメソッド
はじめに
indexメソッドは、リストやタプルの中で、指定した要素が最初に現れる位置(インデックス)を返すメソッド。
サンプルコード
python/index.py at main · ki-hi-ro/python
some_list = [1, 2, 3, 4, 5]
index = some_list.index(3)
print(f"The index of 3 in the list is: {index}")
some_tuple = (10, 20, 30, 40, 50)
index = some_tuple.index(40)
print(f"The index of 40 in the tuple is: {index}")
以下のコードについて解説しよう。some_listに対して、indexメソッドの引数に3を入れたものを使用している。それが変数indexに入る。
some_list = [1, 2, 3, 4, 5]
index = some_list.index(3)
print(f"The index of 3 in the list is: {index}")
次のコードについて解説する。some_tupleに対して、indexメソッドの引数に40を入れたものを使用している。それを変数indexに代入している。
some_tuple = (10, 20, 30, 40, 50)
index = some_tuple.index(40)
print(f"The index of 40 in the tuple is: {index}")
実行結果
hiroki@shibatahiroshitakanoMacBook-Air python % /usr/bin/python3 /Users/hiroki/Documents/python/index.py
The index of 3 in the list is: 2
The index of 40 in the tuple is: 3
3のリスト内におけるインデックス番号は2。
some_list = [1, 2, 3, 4, 5]
40のタプル内におけるインデックス番号は3。
some_tuple = (10, 20, 30, 40, 50)
コメントを残す