檢查索引是否存在於 Python 列表中
Fumbani Banda
2023年1月30日
Python
Python List

我們將介紹兩種使用列表範圍和 IndexError
異常檢查列表索引是否存在的方法。
使用列表範圍檢查索引是否存在於 Python 列表中
我們將不得不檢查索引是否存在於 0 的範圍內和列表的長度。
fruit_list = ["Apple", "Banana", "Pineapple"]
for index in range(0, 5):
if 0 <= index < len(fruit_list):
print("Index ", index, " in range")
else:
print("Index ", index, " not in range")
輸出:
Index 0 in range
Index 1 in range
Index 2 in range
Index 3 not in range
Index 4 not in range
使用 IndexError
檢查索引是否存在於 Python 列表中
當我們嘗試訪問列表中不存在的索引時,它會引發 IndexError
異常。
fruit_list = ["Apple", "Banana", "Pineapple"]
for index in range(0, 5):
try:
fruit_list[index]
print("Index ", index, " in range")
except IndexError:
print("Index ", index, " does not exist")
Index 0 in range
Index 1 in range
Index 2 in range
Index 3 does not exist
Index 4 does not exist
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Fumbani Banda