Python List index()
The index()
method finds the first occurrence of a specified value in a list and returns its index position. If the element doesn’t exist in the list, it raises a ValueError
.
Syntax
list.index(element, start, end)
Parameters
element
: (Required) The item you want to search for in the list.
start
: (Optional) The index from which to begin the search. Default is 0
(beginning of the list).
end
: (Optional) The index to stop the search. The default is the end of the list.
Return Value
The index()
method returns the index of the first occurrence of the specified value. If the value is not found in the list, it raises ValueError
.
Example 1: Find the index of an element
my_list = ["apple", "banana", "mango", "orange"]
# Get the index of banana
index = my_list.index("banana")
print(index) # Output: 1
In Python, the index starts from the position 0
, meaning the first item is at the index 0
, second item is at the index 1
and so on.
Example 2: List with duplicate elements
my_list = [5, 10, 15, 10]
# Get the index of the first occurence of 10
index = my_list.index(10)
print(index) # Output: 1
If a list contains duplicate elements, the index()
method returns the index of the first occurrence of the specified element.
Example 3: Index of element not present in the list
my_list = [5, 10, 15, 20]
# Get the index of 90
index = my_list.index(90)
print(index)
Output:
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
ValueError: 90 is not in list
The index()
raises ValueError
if the element is not present in the list.
Example 4: Using start
and end
parameters of the index()
method
my_list = [10, 20, 10, 30, 10, 40, 50, 60]
# Get the index of the first ocurrence of 10 starting from index 1 and
# ending at index 5
index = my_list.index(10, 1, 5)
print(index) # Output: 2
# Find the index of the first occurrence of 40 from index 3 to the end of the list
index = my_list.index(40, 3)
print(index) # Output: 5
Handling Error
If the item is not found in the list, a ValueError
is raised. To handle this safely, you can use a try
and except
block.
For example:
my_list = [5, 10, 15, 20]
try:
index = my_list.index(25)
print(index)
except ValueError:
print("Item not found")
# Output: Item not found
If you want to find indices of all the occurrences of an element in the list, you should use the list comprehension with the enumerate()
function.