HOWTO · Python

檢查索引是否存在於 Python 列表中

本教程演示了使用列表範圍和 IndexError 異常檢查 Python 列表中是否存在索引

我們將介紹兩種使用列表範圍和 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