python怎么查找列表是否存在该元素
发布时间:2026-03-20 22:14:01

index()法可用于python中查找列表中是否存在某些元素。index() 函数用于从列表中找出一个值的第一个匹配项的索引位置。该方法返回搜索对象的索引位置,如果未找到对象,则抛出异常。
示例:
指定元素的存在:
test_list=[6,3,5,3,4] test_list.index(1)
输出结果:
0
没有指定元素:
test_list=[1,6,3,5,3,4] test_list.index(0)
输出结果如下:
-------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-37-b545efeefee4fceffce5> in <module>
1 test_list = [ 1, 6, 3, 5, 3, 4 ]
----> 2 test_list.index(0)
ValueError: 0 is not in list
请关注Python自学网了解更多Python知识。
下一篇 如何用Python写网页?
