index()是Python中的內置函數,它從列表的開頭搜索給定元素,並返回該元素出現的最低索引。
用法:
list_name.index(element, start, end)
參數:
element - The element whose lowest index will be returned. start (Optional) - The position from where the search begins. end (Optional) - The position from where the search ends.
返回值:
Returns lowest index where the element appears.
錯誤:
If any element which is not present is searched, it returns a ValueError
代碼1:
# Python3 program for demonstration
# of list index() method
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# Will print the index of '4' in list1
print(list1.index(4))
list2 = ['cat', 'bat', 'mat', 'cat', 'pet']
# Will print the index of 'cat' in list2
print(list2.index('cat'))
輸出:
3 0
代碼2:
# Python3 program for demonstration
# of index() method
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# Will print index of '4' in sublist
# having index from 4 to 8.
print(list1.index(4, 4, 8))
# Will print index of '1' in sublist
# having index from 1 to 7.
print(list1.index(1, 1, 7))
list2 = ['cat', 'bat', 'mat', 'cat',
'get', 'cat', 'sat', 'pet']
# Will print index of 'cat' in sublist
# having index from 2 to 6
print(list2.index('cat', 2, 6 ))
輸出:
7 4 3
代碼3:
# Python3 program for demonstration
# of list index() method
# Random list having sublist and tuple also
list1 = [1, 2, 3, [9, 8, 7], ('cat', 'bat')]
# Will print the index of sublist [9, 8, 7]
print(list1.index([9, 8, 7]))
# Will print the index of tuple
# ('cat', 'bat') inside list
print(list1.index(('cat', 'bat')))
輸出:
3 4
代碼4: ValueError
# Python3 program for demonstration
# of index() method error
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
# Return ValueError
print(list1.index(10))
輸出:
Traceback (most recent call last): File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in print(list1.index(10)) ValueError:10 is not in list
注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python list | index()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。