In this tutorial, we are going to learn about the Python list index() method. In Python, the list index() python is a built-in list method that is used to return the index number of the first occurrence of an element.
In the previous tutorial, we have seen all about the Python list extend() method and list count() method.
Headings of Contents
List index() Method
The Python list index()
method is a built-in method, which is used to return the index number of the element at the first occurrence.
Syntax of list index() method:
list.index(element, start, end)
list index() method parameters:
The list index function takes three parameters, element
, start
, and end
:
- Element:- Element to search for.
- Start:- ( Optional ) Start searching from this index number.
- End:- ( Optional ) End the search on this index number.
Return Value of List index() method.
The List index() python returns the index number of the given element to the list.
If the element is not found, the ValueError exception is raised.
Note:- The list index function returns the index number of the only first occurrence of the element.
List index() method example:
Example 1:-
fruits = ['apple', 'banana', 'cherry', 'Mango', 'Papaya', 'cherry']
x = fruits.index('cherry')
print("The index value of \'cherry\':- ", x)
Output
The index value of 'cherry':- 2
If the element is not present in the list, you will get a ValueError.
Example 2:-
lang = ['Python', 'PHP', 'R', 'Ruby', 'Go']
result = lang.index('JavaScript')
print(result)
Output
Traceback (most recent call last):
File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\test.py", line 2, in <module>
result = lang.index('JavaScript')
ValueError: 'JavaScript' is not in list
index() method with start and end parameters:
lang = ['Python', 'PHP', 'R', 'Ruby', 'Go', 'JavaScript', 'Ruby', 'C', 'C++']
#list index method with element parameter.
result = lang.index('PHP')
print(result)
#list index method with element and start parameters.
result1 = lang.index('Ruby', 6)
print(result1)
#list index method with element,start and end parameters.
result2 = lang.index('Ruby', 2, 7)
print(result2)
Output
1
6
3
Conclusion:
In this tutorial, you have learned the Python list index() method to search the index number of a specific element on the first occurrence.
Using the list index method, we can get the index number of elements within a specific range of the index.
I hope you will like the list index() Python post, if you like this article, please comment and share it with your friends who want to become Python a programmer from scratch to advance.
For more information:- Click Here
See Also:
- List append() method
- List clear() method
- List count() method
- List copy() method
- List extend() method
- List insert() method
- List reverse() method
- List pop() method