In Python, index()
method can help you find the index of an element in a list.
How to use index() method?
To get the index of a specific element, we need to pass the argument in the built-in index()
method. Here’s how you would do it:
>> arr = ["Cow", "Dog", "Cat"]
>> print(arr.index("Dog"))
# 1
We can create a helper function if you need to use this frequently.
def getIndex(item, array):
if item in array:
return array.index(item)
else:
return -1
arr = [1, 34, 545, 334]
print(getIndex(334, arr))
# 3
So, this is how you would get the index of specific elements in a list in Python.
I hope you have enjoyed what you’ve read. Thank you for taking the time to read it.