Python Array - Find index of given item
Find Index of Item in Array in Python
In Python, you can find the index of first occurrence of a specific item in a given array using index() method of the array instance.
In this tutorial, you will learn how to find the index of the specified item in a given Python array, with examples.
To find the index of first occurrence of an item x in given array my_array in Python, call the index() method on the array object, and pass the item as argument to the index() method as shown in the following code snippet.
my_array.index(x)
The index() method returns an integer value specifying the index of the given item in the array.
If the item is not present in the array, then the index() throws ValueError.
You can also pass optional start and stop positions for searching the specified item in the array. When these values are given, then the search shall happen within the boundaries set by the start and stop position values. The syntax to pass start and stop index values in given in the following.
my_array.index(x, start)
my_array.index(x, start, stop)
1. Find index of item 20 in the Integer Array
In the following program, we take an integer array my_array with some initial values, and then use index() method to find the index of the item x=20 in this array.
Python Program
import array as arr
my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
x = 20
item_index = my_array.index(x)
print("Item index : ", item_index)
Output
Item index : 2
Explanation
Array : 10, 15, 20, 25, 60, 20, 40
Index : 0 1 2 3 4 5 6
item=20 ↑
index=2
2. Find index of item in the array in specific index bounds
Now, we shall specify a specific start position from which the search operation for the specified item begins.
Python Program
import array as arr
my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
x = 20
start = 3
item_index = my_array.index(x, start)
print("Item index : ", item_index)
Output
Item index : 5
Explanation
Array : 10, 15, 20, 25, 60, 20, 40
Index : 0 1 2 3 4 5 6
start→|
item=20 ↑
index=5
3. Find index of item in the array in specific index bounds, but item not found
Now, we shall specify a specific start and end positions in which the search operation for the specified item has to happen. But, in the given bounds, the item is not present, and therefore, index() method throws ValueError.
Python Program
import array as arr
my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
x = 20
start = 3
stop = 4
item_index = my_array.index(x, start, stop)
print("Item index : ", item_index)
Output
ValueError: array.index(x): x not in array
Explanation
Array : 10, 15, 20, 25, 60, 20, 40
Index : 0 1 2 3 4 5 6
start→| |←stop
item=20 not found
Summary
In this Python Array tutorial, we learned how to find the index of first occurrence of a specific item in the given array in Python, using index() method, with examples.