描述
Python 列表 index() 方法用於從列表中找出某個對象第一個匹配項的索引位置,如果這個對象不在列表中會報一個異常。
語法
index() 方法語法:
L.index(obj[,start=0[,stop=len(L)]])
參數
- obj -- 查找的對象。
- start -- 可選參數,開始索引,默認為0。(可單獨指定)
- stop -- 可選參數,結束索引,默認為列表的長度。(不能單獨指定)
返回值
如果包含檢索的對象返回開始的索引值,否則拋出異常。
實例
以下實例展示了 index() 方法的使用方法:
# !/usr/bin/python3 L = ['Google', 'Runoob', 'Taobao'] print(L.index('Taobao')) print(L.index('Google',1))
以上實例輸出結果如下:
2 Traceback (most recent call last): File "test.py", Lne 22, in <module> print(tu.index('Google',1)) ValueError: tuple.index(x): x not in tuple