Use the list index() method to Find the index of an element in the array Python. It returns the index in the list where the first instance of the value
passed in is found.
list.index(element)
It returns the index of the first occurrence of the element that you want to find, or -1 if the element is not found.
Find the index of an element in an array of Python
Simple example code.
animals = ['cat', 'dog', 'rabbit', 'horse']
# get the index of 'dog'
index = animals.index('dog')
print("dog", index)
print("rabbit", animals.index('rabbit'))
Output:
If you want to find all occurrences of an element in an array, you can use a list comprehension:
my_array = [10, 20, 30, 40, 30, 50]
element_to_find = 30
indices_of_element = [index for index, value in enumerate(my_array) if value == element_to_find]
if indices_of_element:
print(f"The indices of {element_to_find} are: {indices_of_element}")
else:
print(f"{element_to_find} is not in the array.")
This code uses enumerate()
to get both the index and the value of each element in the array. Then, it creates a list of indices where the element is found.
Do comment if you have any doubts or suggestions on this Python Array.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.