Skip to content
Advertisement

Get items from list if the item contains any of the strings in another list (Python) [closed]

I have a list that looks like:

a_list = ['abc','acd','ade','bef','fba','adf','fac']

I would like all items in the list if it contains ab or ac. From the example above, I would like the list to be:

b_list = ['abc','acd','fac']

I have tried the following, but it gives me a TypeError.

b_list = [x for x in a_list if any(['ab','ac']) in x]

Advertisement

Answer

You’re almost there but you can’t cross check multiple substrings against a string. What you can do is use two conditions with an or:

b_list = [x for x in a_list if 'ab' in x or 'ac' in x]

If you have a list of substrings to check, you can use any() in your condition but you’ll have to iterate over the substrings:

subs   = ('ab','ac')
b_list = [x for x in a_list if any(s in x for s in subs)]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement