Reputation: 205
I'm sure this is simple and I'm looking right at it, but I cannot make it work.
Goal: Use a loop to go through the list of strings and find the search term. Return the element number of the first match.
I've tried a few options, nothing seems to work, and I have yet to find a working description of how to do it in any texts.
This is my best attempt so far:
def get_element_number(a_list, search_term):
for i in range(len(a_list)):
if search_term in a_list[i]:
return a_list.index(i)
elif not search_term in a_list:
return 'no match'
Error message:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 5, in get_element_number
ValueError: 2 is not in list
Not looking for the complete answer, just any help in where I'm going wrong or if I'm missing something would be very helpful.
Upvotes: 2
Views: 6073
Reputation: 72
def find_element(a_list, search_term):
i = 0
for e in a_list:
if e == search_term:
return i
i += 1
return -1
Very nice explanation for either this one or other solution you can find in the video linked below
https://www.youtube.com/watch?time_continue=216&v=GwOFHuPMCpM
Upvotes: 0
Reputation: 5714
Here's a simple change to your code that will resolve it:
def get_element_number(a_list, search_term):
if search_term in a_list: #if search keyword is in the list
return a_list.index(search_term) #then return the index of that
else:
return 'no match!'
Upvotes: 0
Reputation: 12168
def get_element_number(a_list, search_term):
for index, value in enumerate(a_list):
if search_term in value:
return index
return 'not match'
Upvotes: 0
Reputation: 1445
for index, s in enumerate(a_list):
if s == term:
return index
return -1
Upvotes: 0
Reputation: 2950
You can replace all of this with index = a_list.index(search_term)
.
Note that if the list doesn't contain the search_term, it will throw an exception, so you'll need to catch that and return "not found" or something similar. Second note: it only returns the first index of the found search_term.
Upvotes: 3
Reputation: 140256
if search_term in a_list[i]:
is True
even if search_term
is contained in a_list[i]
.
So in the case of an exact match index
works, but in a case of a partial match index
throws an exception.
Aside: elif not search_term in a_list:
is wrong. Remove it or you'll return at first non-match.
Rewrite it as:
def get_element_number(a_list, search_term):
try:
return a_list.index(search_term)
except IndexError:
'no match'
This is simpler and has the advantage of performing search only once, which is important performance-wise when you're using linear search (not taking the overhead of exception into account).
Upvotes: 3