find the index of an element in an array in python

To find the index of an element in an array, you can use the index() method. This method returns the index of the first occurrence of the specified element in the array.

Here is an example:

main.py
my_array = [10, 20, 30, 40, 50]
element_to_find = 30

index_of_element = my_array.index(element_to_find)

print("The index of {} is {}".format(element_to_find, index_of_element))
179 chars
7 lines

In this example, we have an array my_array that contains five integers. We want to find the index of the element 30 in the array. We use the index() method to find the index of the first occurrence of 30 in the array. The index is stored in the variable index_of_element. We then print out the index using string formatting.

Output:

main.py
The index of 30 is 2
21 chars
2 lines

Note that if the element to find is not in the array, the index() method will raise a ValueError. Therefore, it's a good practice to use a try...except block to handle such cases.

gistlibby LogSnag