The Python Oracle

Check if multiple strings exists in list using Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 Check If Multiple Strings Exists In List Using Python
00:38 Accepted Answer Score 12
00:56 Answer 2 Score 0
01:36 Thank you

--

Full question
https://stackoverflow.com/questions/4761...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 12


You have to check if all of the strings in the first list is contained by any string in the second list:

def all_exist(avalue, bvalue):
    return all(any(x in y for y in bvalue) for x in avalue)

items = ['greg','krista','marie']
print(all_exist(['greg', 'krista'], items)) # -> True
print(all_exist(['gre', 'kris'], items))    # -> True
print(all_exist(['gre', 'purple'], items))  # -> False
print(all_exist([], items))                 # -> True



ANSWER 2

Score 0


We want to loop through the elements in avalue and check if this element is in any of the strings in bvalue. But we want to do all of that inside all as we want to check that all elements in avalue have a match.

Also, if we do the test this way, an empty avalue will return True anyway, so we don't need to tell Python to explicitly do this.

Note that: since you have defined all_exist as a function, it should really return a value, not print the result, so I have changed that for you:

def all_exist(avalue, bvalue):
    return all(any(i in j for j in bvalue) for i in avalue)

and some testing shows it works:

>>> all_exist(['greg', 'krista'], items) # true
True
>>> all_exist(['gre', 'kris'], items) # true
True
>>> all_exist(['gre', 'purple'], items) # false
False