I have a list that looks like:
JavaScript
x
2
1
a_list = ['abc','acd','ade','bef','fba','adf','fac']
2
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:
JavaScript
1
2
1
b_list = ['abc','acd','fac']
2
I have tried the following, but it gives me a TypeError
.
JavaScript
1
2
1
b_list = [x for x in a_list if any(['ab','ac']) in x]
2
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
:
JavaScript
1
2
1
b_list = [x for x in a_list if 'ab' in x or 'ac' in x]
2
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:
JavaScript
1
3
1
subs = ('ab','ac')
2
b_list = [x for x in a_list if any(s in x for s in subs)]
3