Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any item in a list occurs in another list?

Tags:

python

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;
like image 562
Rolando Avatar asked Dec 27 '22 01:12

Rolando


1 Answers

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)
like image 104
David Robinson Avatar answered Mar 16 '23 03:03

David Robinson