If I have the following list:
listA = ["A","Bea","C"]
and another list
listB = ["B","D","E"]
stringB = "There is A loud sound over there"
What is the best way to check if any item in listA occurs in listB or stringB, if so then stop? I typically use for loop to iterate over each item in listA to do such a thing, but are there better ways syntactically?
for item in listA:
if item in listB:
break;
For finding the overlap of two lists, you can do:
len(set(listA).intersection(listB)) > 0
In if
statements you can simply do:
if set(listA).intersection(listB):
However, if any items in listA
are longer than one letter, the set approach won't work for finding items in stringB
, so the best alternative is:
any(e in stringB for e in listA)
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