Python中list.index()方法是一个查找列表元素的方法,可以返回某个元素的索引值,其语法格式为:list.index(x, start, end),其中x为要查找的元素,start为查找起始位置,end为查找结束位置。
使用示例
以下实例展示了list.index()方法的使用:
#!/usr/bin/python # -*- coding: UTF-8 -*- list1 = ['Google', 'Runoob', 'Taobao'] print(list1.index('Runoob'))
以上实例输出结果为:
1
以下实例展示了list.index()方法的start参数使用:
#!/usr/bin/python # -*- coding: UTF-8 -*- list1 = ['Google', 'Runoob', 'Taobao', 'Google'] print(list1.index('Google', 1))
以上实例输出结果为:
3
以下实例展示了list.index()方法的start和end参数使用:
#!/usr/bin/python # -*- coding: UTF-8 -*- list1 = ['Google', 'Runoob', 'Taobao', 'Google'] print(list1.index('Google', 1, 3))
以上实例输出结果为:
2
注意事项
- 如果x不在列表中,则会抛出ValueError异常。
- start和end参数默认值为0和len(list),即默认从列表的第一个元素开始查找,查找到一个元素结束。
- start参数必须小于end参数。