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.py179 chars7 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.py21 chars2 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