リスト.index() / リスト.count() / in演算子
| 対応: | Python 2(2000) |
|---|
リスト内の要素を検索したり、特定の値が含まれるかどうかを確認するメソッドと演算子です。
構文
# 値と一致する最初の要素のインデックスを返す リスト.index(値, 開始=0, 終了=len(リスト)) # 値と一致する要素の個数を返す リスト.count(値) # リストに値が含まれるか確認する(True / False) 値 in リスト 値 not in リスト
関数一覧
| メソッド・演算子 | 概要 |
|---|---|
| list.index(x, start, end) | リスト内で最初に値 x が見つかったインデックスを返します。見つからない場合は ValueError が発生します。 |
| list.count(x) | リスト内で値 x と一致する要素の個数を返します。存在しない場合は 0 を返します。 |
| x in list | リストに値 x が含まれる場合は True、含まれない場合は False を返します。 |
| x not in list | リストに値 x が含まれない場合は True、含まれる場合は False を返します。 |
サンプルコード
list_index_count_1.py
# index() で要素のインデックスを取得する
members = ["item_a", "item_b", "item_c", "item_b", "item_d"]
print(members.index("item_b")) # 1
print(members.index("item_b", 2)) # 3
実行すると次のように出力されます。
python3 list_index_count_1.py 1 3
list_index_count_2.py
# count() で値の出現回数を調べる
members = ["item_a", "item_b", "item_c", "item_b", "item_d", "item_b"]
print(members.count("item_b")) # 3
print(members.count("item_e")) # 0
# in 演算子で要素の存在確認をする
print("item_a" in members) # True
print("item_e" in members) # False
print("item_e" not in members) # True
実行すると次のように出力されます。
python3 list_index_count_2.py 3 0 True False True
list_index_count_3.py
# 存在確認してから index() を使うのが安全
members = ["item_a", "item_b", "item_c", "item_d", "item_e"]
target = "item_c"
if target in members:
print(members.index(target)) # 2
# 存在しない値を検索すると ValueError が発生します。
try:
members.index("item_x")
except ValueError:
print("item_x はリストにありません。")
# all/any との組み合わせ例
scores = [80, 90, 75, 88]
print(all(s >= 60 for s in scores)) # True
print(any(s >= 90 for s in scores)) # True
実行すると次のように出力されます。
python3 list_index_count_3.py 2 item_x はリストにありません。 True True
よくあるミス
よくあるミス1: 存在確認なしに index() を呼ぶ
値がリストにない場合、index() は ValueError を送出します。in 演算子で事前確認するか、try-except で例外を捕捉する方法があります。
members = ["item_a", "item_b", "item_c"]
print(members.index("item_e")) # ValueError
次のように記述します。
members = ["item_a", "item_b", "item_c"]
if "item_e" in members:
print(members.index("item_e"))
else:
print("item_e はリストにありません。")
よくあるミス2: count() を存在確認として使う
count() は要素の個数を返す関数です。存在確認には in 演算子を使うほうがシンプルで意図が伝わりやすいです。
members = ["item_a", "item_b", "item_c"]
if members.count("item_b") > 0: # 冗長な書き方
print("item_b はいます。")
次のように記述します。
members = ["item_a", "item_b", "item_c"]
if "item_b" in members: # シンプルで意図が明確
print("item_b はいます。")
概要
『index()』は最初に一致した要素のインデックスを返します。値が存在しない場合は『ValueError』が発生するため、使用前に『in』演算子で存在確認を行うか、try-exceptで例外を処理する方法があります。
『in』演算子はリストの全要素を順番に比較する線形探索(O(n))を行います。大量のデータを頻繁に検索する場合は、リストの代わりに『set』(集合)を使うと平均O(1)で検索できます。検索が主目的のデータには、リストよりセットや辞書の方が適しています。
リストをソートした後に検索を行う場合は、Pythonの標準ライブラリ『bisect』モジュールを使った二分探索(O(log n))がより高速です。要素の並べ替えについては『リスト.sort() / リスト.reverse()』を参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。