4

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?

4
  • 1
    Problem is that you return True as soon as you find the first element that is in both a and b Commented Feb 25, 2014 at 10:49
  • 1
    Do you need a list of flags to check one-by-one if an element of a exists in b, or only one bool if ALL elements of a exist in b? Commented Feb 25, 2014 at 10:49
  • Flag should be raised only when all elements in a exist in b. Commented Feb 25, 2014 at 10:51
  • 1
    Use the correct data structure, use docs.python.org/2/library/sets.html Commented Feb 25, 2014 at 10:56

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.