I have two lists with not fixed number of items, e. g.:
data=['sun','stars','moon','supermoon','planet','comet','galaxy']
forbidden=['mo','st','lax']
I need to print only those items of data
which do not contain any of the strings listed in forbidden
. In this case the output would be
sun
planet
comet
What I tried is
print [x for x in data if forbidden not in x ]
which works only for one condition (one item in forbidden
list)
Is there any way how to check all the conditions at once?
In case I knew the number of items in forbidden
I could use
print [x for x in data if forbidden[0] not in x and forbidden[1] not in x]
but it does not work with unknown number of items.
Thank you for help.
You can use all
:
data=['sun','stars','moon','supermoon','planet','comet','galaxy']
forbidden=['mo','st','lax']
print([i for i in data if all(c not in i for c in forbidden)])
Output:
['sun', 'planet', 'comet']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With