当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python list index()用法及代码示例


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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。