Python3 list.index()方法

index()方法返回obj是否出現列表中的最低索引。

語法

以下是 index()方法的語法 -
list.index(obj)

參數

  • obj -- 這是要查找的對象。

返回值

此方法返回找到的對象的索引,如果指定值沒有找到,則拋出一個異常。

示例

下麵的示例顯示index() 方法的使用。
#!/usr/bin/python3

list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))

當我們運行上面的程式,會產生以下結果 -
Traceback (most recent call last):
  File "test.py", line 3, in
    print ('Index of C#', list1.index('C#'))
ValueError: 'C#' is not in list

上一篇: Python3字串 下一篇: Python3列表