Reputation: 39
I have a function that checks if a given string is in a list of strings using a for and while loop. I’m not supposed to use the ‘in’ operator. Here’s my code using a for loop:
def word_in_list(words, word):
for strings in words:
if len(words) > 0 and strings == word:
return True
else:
return False
However, it is not returning True unless the single string is the first element of the list. The list should return False in case the list is empty. And how can I solve the same problem using a while loop (and without 'in' operator)?
Upvotes: 0
Views: 5163
Reputation: 2343
Your else block kicks-in without finishing the iteration on complete list.
def word_in_list(list_of_words, word_to_search):
found = False
for word in list_of_words:
if word == word_to_search:
found = True
break # breaks iff the word is found
return found
Any particular reason you are adamant not to use the 'in' operator? Also, please be careful about the indentation in the code you paste.
Upvotes: 0
Reputation: 64
simly use this code
def word_in_list(words, word):
if word in words:
return True
else
return False
Upvotes: 0
Reputation: 8564
Don’t return False
the moment you find one mismatch, return False
when you are done checking all possibilities and not finding any match:
def word_in_list(words, word):
for strings in words:
if strings == word:
return True
return False
Also, no need to check the length of list every time, if it's zero, you don't run the loop at all and directly return False
.
Upvotes: 1
Reputation: 485
Your code is wrong because of the else statement. Your function must return False only after checking the whole list, not just the first element. Whenever a function gets to a "return" instruction, it stops, so it just checked the first one. This is the correct solution:
def word_in_list(words, word):
i = 0
while i < len(words):
if words[i] == word:
return True
i += 1
return False
Upvotes: 0