Open In App

Find Index of Element in Array - Python

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform numerical operations on elements.

Python’s array module allows to create and manipulate arrays which are especially useful in applications that require large datasets or scientific computing.

Using index() Method

index() method is a straightforward and built-in approach to finding the index of an element in an array. It is simple to use and works well when we know the element exists in the array. It's efficient for arrays that do not have duplicate elements since it returns the first occurrence of the element.

Python
import array

arr = array.array('i', [10, 20, 30, 40, 50])

# Find the index of the element 30
idx = arr.index(30)
print(idx) 

Output
2

Let's look at other cases of finding the index of an element in an array in python:

Using List Comprehension for Multiple Occurrences

If we want to find all occurrences of an element in the array, we can use a list comprehension. This method is more efficient than manually looping through the array when we need to collect multiple indexes.

Python
import array

arr = array.array('i', [10, 20, 30, 20, 50])

# Find all indices of 20
li = [i for i, x in enumerate(arr) if x == 20]
print(li)  

Output
[1, 3]

Use this method when we need to find all occurrences of a specific element in an array.

Using Loop to Find the Index

If we want more control over the process or if we're working with arrays where we need to find the index of multiple occurrences of an element, a loop can be a good choice.

Python
import array

arr = array.array('i', [10, 20, 30, 20, 50])

# Loop through the array to find the index of 20
for i in range(len(arr)):
    if arr[i] == 20:
        print(i)
        break

Output
1

This approach is useful when we're working with arrays that may contain duplicate elements and we want to find the first match or all occurrences.


Next Article
Practice Tags :

Similar Reads