Python Array index() Method



The Python array index() method returns smallest index value of the first occurrence of element in an array.

Syntax

Following is the syntax of the Python array index method −

array_name.index(element, start, stop)

Parameters

This method accepts following parameters.

  • element : It can be int, float, string, double etc.
  • start(optional) : start searching an element from that particular index.
  • stop(optional) : stop searching an element at that particula index.

Example 1

Following is the basic example of Python array index method −

import array as arr 
my_arr1 = arr.array('i',[13,32,52,22,3,10,22,45,39,22])
x = 22
index  =my_arr1.index(x)
print("The index of the element",x,":",index)

Output

Following is the output of the above code −

The index of the element 22 : 3

Example 2

In this method, we can search the element with in the range of index following is the example −

import array as arr
my_arr2 = arr.array('i',[13,34,52,22,34,3,10,22,34,45,39,22])
x = 34
#searching the element with in given range
index = my_arr2.index(x,2,6)
print("The index of the element", x, "within the  given range", ":",index)

Output

Following is the output of the above code −

The index of the element 34 within the  given range : 4

Example 3

When we try to find the element, which is not present in an array we get Value error.

Here, we have created an array of double datatype and we are trying to find the element which is not present in the array we got error

import array as arr
my_arr3 = arr.array('d',[1.4,2.9,6.6,5.9,10.5,3.4])
x = 34
#searching the element with in given range
index = my_arr3.index(x)
print("The index of the element", x, "within the  given range", ":",index)

Output

Traceback (most recent call last):
  File "E:\pgms\Arraymethods prgs\index.py", line 27, in <module>
    index = my_arr3.index(x)
          ^^^^^^^^^^^^^^^^
ValueError: array.index(x): x not in array

Example 4

In this method, we can start searching an element from specified index value following is the example −

import array as arr
my_arr4 = arr.array('d',[1.4, 2.9, 3.4, 5.9, 10.5, 3.4, 7.9])
x = 3.4
#Searching from specified index
index = my_arr4.index(x,5)
print("The index of the element", x, "within the  given range", ":",index)

Output

The index of the element 3.4 within the  given range : 5
python_array_methods.htm
Advertisements