Comparing two lists in python if elements exist

I have two lists where I want to check if elements from a to b exist

a=[1,2,3,4]
b=[4,5,6,7,8,1]

This is what I tried (didn't work though!)

a=[1,2,3,4]
b=[4,5,6,7,3,1]

def detect(list_a, list_b):
    for item in list_a:
        if item in list_b:
            return True
    return False  # not found

detect(a,b)

I want to check if the elements from a to b exist and set the flag accordingly. Any thoughts?

+3
source share
1 answer

Your code is returned as soon as the first element exists in both lists. To check all the elements, you can try this, for example:

def detect(list_a, list_b):
    return set(list_a).issubset(list_b)

Another possibility without creating set:

def detect(list_a, list_b):
    return all(x in list_b for x in list_a)

And in case you were curious what exactly is wrong in your code, this is a fix in its current form (but this is not very pythonic):

def detect(list_a, list_b):
    for item in list_a:
        if item not in list_b:
            return False       # at least one doesn't exist in list_b

    return True   # no element found that doesn't exist in list_b
                  # therefore all exist in list_b

, , . detect . , isSubset ..

+7

All Articles