1.使用下標直接訪問列表元素,如果指定下標不存在,則拋出異常。
>>> alist[3]
1
>>> alist[3]=5.5
>>> alist
[1, 3, 5, 5.5, 3, 5, 1, 3, 5]
>>>
>>> alist[15]
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
alist[15]
IndexError: list index out of range
2.使用列表對象的index()方法獲取指定元素首次出現的下標,若列表對象中不存在指定元素,則拋出異常。
>>> alist
[1, 3, 5, 5.5, 3, 5, 1, 3, 5]
>>> alist.index(3)
1
>>> alist.index(100)
Traceback (most recent call last):
File "<pyshell#102>", line 1, in <module>
alist.index(100)
ValueError: 100 is not in list
3.count()方法統計指定元素在列表對象中出現的次數
>>> alist
[1, 3, 5, 5.5, 3, 5, 1, 3, 5]
>>> alist.count(3)
3
>>> alist.count(5)
3
>>> alist.count(4)
0
