index() 是 Python 列表用於查找元素首次出現位置的方法,回傳該元素的索引(從 0 起算)。若元素不存在,會拋出 ValueError 例外,這是新手最常踩的坑。本文詳細說明語法、參數、回傳值、例外處理模式與進階搜尋技巧。
list.index(obj[, start[, end]])
== 比較)ValueError: 'x' is not in list#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc']
print("Index for xyz :", aList.index('xyz')) # 1
print("Index for zara :", aList.index('zara')) # 2
# 指定搜尋範圍
lst = ['a', 'b', 'c', 'b', 'd']
print(lst.index('b', 2)) # 3(從索引 2 開始找)
print(lst.index('b', 0, 3)) # 1(索引 0 到 2 範圍內)
def safe_index(lst, value, default=-1):
try:
return lst.index(value)
except ValueError:
return default
lst = [1, 2, 3]
print(safe_index(lst, 2)) # 1
print(safe_index(lst, 99)) # -1(不拋出例外)
lst = [1, 2, 3]
value = 99
if value in lst:
idx = lst.index(value)
print(f"找到於索引 {idx}")
else:
print("不存在")
def find_index(lst, predicate):
"""依自訂條件函式尋找索引"""
for i, x in enumerate(lst):
if predicate(x):
return i
return -1
lst = [{'id':1}, {'id':2}, {'id':3}]
print(find_index(lst, lambda x: x['id'] == 2)) # 1
def all_indices(lst, value):
return [i for i, x in enumerate(lst) if x == value]
lst = ['a', 'b', 'c', 'b', 'd']
print(all_indices(lst, 'b')) # [1, 3]
# 方法一:反轉列表後搜尋
lst = ['a', 'b', 'c', 'b', 'd']
last_idx = len(lst) - 1 - lst[::-1].index('b')
print(last_idx) # 3
# 方法二:rindex 不存在,手動實作
def rindex(lst, value):
for i in range(len(lst)-1, -1, -1):
if lst[i] == value:
return i
raise ValueError(f"{value} not in list")
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 只在索引 3 到 7 之間找 5
try:
idx = lst.index(5, 3, 8) # 找到索引 5
print(idx)
except ValueError:
print("區間內不存在")
{v:i for i,v in enumerate(lst)}(O(1) 查詢,但需額外記憶體且不支援重複值)
# 陷阱 1:不存在時拋出例外(最常見錯誤)
lst = [1, 2, 3]
lst.index(4) # ValueError: 4 is not in list
# 陷阱 2:只回傳「第一個」匹配索引
lst = ['a', 'b', 'a', 'c']
print(lst.index('a')) # 0,而非 [0, 2]
# 陷阱 3:start/end 參數為索引,非元素值
lst = [10, 20, 30, 40]
lst.index(30, 20) # 錯誤!20 被視為 start 索引(超出範圍)
# 正確:
lst.index(30, 2) # 從索引 2 開始找
# 陷阱 4:可變物件比較用 ==(內容相等即視為同一)
a = [1, 2]
lst = [a, [1, 2], [3, 4]]
print(lst.index([1, 2])) # 0(找到第一個內容相等的)
| 方法 | 用途 | 回傳 | 不存在時 |
|---|---|---|---|
| list.index(x) | 找第一個索引 | int | ValueError |
| x in list | 檢查存在性 | bool | False |
| list.count(x) | 統計出現次數 | int | 0 |
| enumerate + 條件 | 自訂邏輯找索引 | int/自訂 | 自訂 |
| dict 映射 | 大量 O(1) 查詢 | int | KeyError |
index() 是尋找列表元素首次出現索引的標準方法,語法為 list.index(obj, start, end)。核心注意點:不存在會拋出 ValueError,務必用 in 檢查或 try/except 處理。掌握區間搜尋、反向搜尋、全索引搜尋等進階技巧,並理解其 O(n) 特性,能在資料處理、演算法實作中靈活運用。