Python 3 列表方法 index( )
Python 3.8.5
语法格式:
list.index(x[, start[, end]])
描述:
- 返回列表中元素 x 第一次出现时的索引。
- 如果没有元素 x,则会抛出 ValueError 异常。
参数说明:
- x —— 查找的对象;
- start —— 可选,查找的起始位置;
- end —— 可选,查找的结束位置。
返回值:
- 该方法返回查找对象的位置索引,如果没有找到对象则抛出异常。
示例:
>>> list1 = [1, 'A', 'DD', 'C', 'A', 'N', 'B', 'A']
>>> list1.index('A')
1
>>> list1.index('A', 5)
7
>>> list1.index('A', 2, 5)
4
>>> list1.index('A', -6, -1) # 如果要反向表示索引,依然是起始位置的索引要小于终止位置的索引值
4 # 返回的位置索引都是正向表示
>>> list1.index('A', -1, -6)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
list1.index('A', -1, -6)
ValueError: 'A' is not in list