Python list | index()
index() is an inbuilt function in Python, which searches for a given element from the start of the list and returns the lowest index where the element appears.
list_name.index(element, start, end)
element - The element whose lowest index will be returned. start (Optional) - The position from where the search begins. end (Optional) - The position from where the search ends.
Returns lowest index where the element appears.
If any element which is not present is searched, it returns a ValueError
Code #1 :
Code #2 :
7 4 3
Code #3 :
Code #4 : ValueError
Traceback (most recent call last): File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in print(list1.index(10)) ValueError: 10 is not in list
Code #5 : When 2 arguments are passed
When two arguments are passed in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins.
list_name.index(element , start)
Code #6: The end index passed as argument is not included
The third argument which is the end, itself is not included in the range from start to end, i.e the searching takes place from start to end-1 index.
Traceback (most recent call last): File "/home/3cbe5b7d0595ab3f8564f16af7a15172.py", line 9, in <module> print(list1.index(9 , 1 , 4)) ValueError: 9 is not in list
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course