Finding the First Instance of an Element in an Array

Finding the First Instance of an Element in an Array

Need help finding the first instance of an element in an array? I recently came across a situation where I had two arrays with corresponding data in each array. For example, I had two arrays where one was a person’s first name and the other was a person’s last name. I needed to find a person’s first name given a person’s last name.

first_name = ['Bill', 'Mike', 'Amanda', 'Jill']
last_name = ['Richardson', 'Marlow', 'Gutierres', 'Willerby']

I knew that every element in the last_name array was distinct and needed to find a person’s first name from their last. So given Marlow, what was their first name? In this case, it would be Mike. One can do this programmatically in python with the index array method. We essentially need to find an element’s location in an 1 dimensional array and then use that vertices, to pull our first name.

name = first_name[last_name.index('Marlow')]
print name
output: 'Mike'

Note that the last name array needs to be distinct or else it will find the index of the first instance of Marlow and return Mike while you may be looking for that second person. Also, it might be worthwhile to check that both arrays are the same size by using len. If they aren’t the same size, then everybody doesn’t have the a first name.

if len(first_name)!= len(last_name):
    print('Somebody doesnt have a first name!')
else:
    name = first_name[last_name.index('Marlow')]
    print(name)

Happen to be making a DataFrame with that array? Make sure to check out the error covered in this article to avoid making some easy mistakes. Cheers and happy coding.

Leave a Comment