Python 列表 index()

index() 方法返回 列表中指定元素的索引。

示例

animals = ['cat', 'dog', 'rabbit', 'horse']

# get the index of 'dog' index = animals.index('dog')
print(index) # Output: 1

列表 index() 的语法

列表 index() 方法的语法是

list.index(element, start, end)

列表 index() 参数

列表 index() 方法最多可以接受三个参数

  • element - 要搜索的元素
  • start(可选)- 从此索引开始搜索
  • end(可选)- 在此索引之前搜索元素

列表 index() 的返回值

  • index() 方法返回列表中给定元素的索引。
  • 如果未找到元素,则会引发 ValueError 异常

注意:index() 方法只返回匹配元素的第一次出现。


示例 1:查找元素的索引

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index) # element 'i' is searched # index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)

输出

The index of e: 1
The index of i: 2

示例 2:列表中不存在的元素的索引

# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']

# index of 'p' is vowels
index = vowels.index('p')
print('The index of p:', index)

输出

ValueError: 'p' is not in list

示例 3:带 start 和 end 参数的 index() 工作原理

# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']

# index of 'i' in alphabets
index = alphabets.index('e') # 1
print('The index of e:', index) # 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index) # 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)

输出

The index of e: 1
The index of i: 6
Traceback (most recent call last):
  File "*lt;string>", line 13, in 
ValueError: 'i' is not in list

另请阅读:使用 for 循环访问列表索引的 Python 程序

在结束之前,让我们测试一下您对 Python 列表 index() 的知识!您能解决以下挑战吗?

挑战

编写一个函数来查找列表中给定元素的索引。

  • 例如,对于输入 [1, 2, 3, 4, 5]3,输出应为 2
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战