Open In App

Find index of element in array in python

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we are looking for.

Python
a = [10, 20, 30, 40, 50]

# Find the index of the element 30 in the list 'a'
idx = a.index(30)
print(idx)

Output
2

Note: If the element is not found, Python raises a ValueError. We can handle this using a try and except block.

Let's look into various other methods which we can use to find index of element in array in python is using a simple for loop.

Using numpy.where() for Arrays

For numerical arrays, numpy provides an efficient method using numpy.where().

Python
import numpy as np

arr = np.array([10, 20, 30, 40, 30, 50])
element = 30

# Find indices
indices = np.where(arr == element)[0]

print("Indices:", indices)

Output
Indices: [2 4]

Using for loop

We can use a similar for with lists to search for an element by looping through the list. Here’s how we can do that:

Python
arr = [10, 20, 30, 40, 50]
element = 40
idx = -1

for i in range(len(arr)):
    if arr[i] == element:
        idx = i
        break

print(idx)

Output
3

Using List Comprehension with enumerate()

Find all indices of an element using list comprehension With enumerate().

Python
a = [10, 20, 30, 40, 30, 50]
element = 30

# Find all indices
indices = [i for i, val in enumerate(a) if val == element]

print("Indices:", indices)

Output
Indices: [2, 4]

Next Article

Similar Reads