7

How can i test if multiple strings exist in another list? Below is a code example that I started with but doesn't work properly. It should return true if even part of the string is found in the list.

I marked in the comments what the result should return. as you can see they all fail though.

def all_exist(avalue, bvalue):
    if avalue == []:
        return True
    else:
        print (all(x in avalue for x in bvalue))

items = ['greg','krista','marie']
all_exist(['greg', 'krista'], items) # true
all_exist(['gre', 'kris'], items) # true
all_exist(['gre', 'purple'], items) # false

Would it be better to convert the second list to a single string and then just test if strings in list exist in it?

2
  • what is "even part of the string"? Do you mean any part of the string?
    – Joe Iddon
    Commented Dec 2, 2017 at 20:59
  • correct, so 'gre' shoud return true since the list of items contains 'greg' Commented Dec 2, 2017 at 21:02

2 Answers 2

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
2
  • 2
    for the win!!! im making a search filter and this is how i would prefer it to work. thank you Commented Dec 2, 2017 at 21:06
  • If i understand it correctly, the: "any(x in y for y in bvalue) for x in avalue" part of that function is actually surrounded by extra "(" to create a generator. Which serves as the parameter for the all() function. But they are redundant to set here. Commented Jan 18, 2019 at 8:41
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.