Python list Method - index()
The index()
method in Python is a built-in method used to get the index of the first occurrence of an element in a list.
Syntax:
list_name.index(element, start, end)
Here, element
is the element whose index is to be found, start
is the optional starting index (inclusive), and end
is the optional ending index (exclusive) of the search. If element
is not found in the list, a ValueError
is raised.
Example:
my_list = [1, 2, 3, 2] print(my_list.index(2)) # Output: 1
In the above example, the index()
method is used to find the index of the first occurrence of the element 2
in the list my_list
. The method returns the index 1
, which is the index of the first occurrence of 2
in my_list
.
We can also provide the optional start
and end
arguments to limit the search to a specific range in the list. For example,
my_list = [1, 2, 3, 2] print(my_list.index(2, 2)) # Output: 3
In the above example, the index()
method is used to find the index of the first occurrence of the element 2
in the list my_list
, starting the search from the index 2
. The method returns the index 3
, which is the index of the first occurrence of 2
after the index 2
in my_list
.