Reputation: 4497
I want to check if a word is in a list of words.
word = "with"
word_list = ["without", "bla", "foo", "bar"]
I tried if word in set(list)
, but it is not yielding the wanted result due to the fact in
is matching string rather than item. That is to say, "with"
is a match in any of the words in the word_list
but still if "with" in set(list)
will say True
.
What is a simpler way for doing this check than manually iterate over the list
?
Upvotes: 3
Views: 7091
Reputation: 63729
You could also create a single search string by concatenating all of the words in word_list into a single string:
word = "with"
word_list = ' '.join(["without", "bla", "foo", "bar"])
Then a simple in
test will do the job:
return word in word_list
Upvotes: 0
Reputation: 85603
in
is working as expected for an exact match:
>>> word = "with"
>>> mylist = ["without", "bla", "foo", "bar"]
>>> word in mylist
False
>>>
You can also use:
milist.index(myword) # gives error if your word is not in the list (use in a try/except)
or
milist.count(myword) # gives a number > 0 if the word is in the list.
However, if you are looking for a substring, then:
for item in mylist:
if word in item:
print 'found'
break
btw, dont use list
for the name of a variable
Upvotes: 3
Reputation: 45039
You could do:
found = any(word in item for item in wordlist)
It checks each word for a match and returns true if any are matches
Upvotes: 9