Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two lists in python if elements exist

Tags:

python

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

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 elements from a exists in b and should set a flag accordingly. Any thoughts?

like image 487
user741592 Avatar asked Sep 20 '25 14:09

user741592


1 Answers

Your code returns as soon as first element exists in both lists. To check all elements you could try this for example:

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

Other possibility, without creating a 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 in your code is wrong, this is the fix in its current form (but it's 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

And finally, your function name isn't very readable. detect is too ambiguous. Consider other more verbose names, like isSubset etc.

like image 53
BartoszKP Avatar answered Sep 22 '25 04:09

BartoszKP