0

I have recently started working with Python. I know it might be a silly question as it sounds very basic question to me.

I need to compare first list with second list and if first list values are there in the second list, then I want to return true.

children1 = ['test1']
children2 = ['test2', 'test5', 'test1']

if check_list(children1):
    print "hello world"


def check_list(children):
    # some code here and return true if it gets matched.
    # compare children here with children2, if children value is there in children2
    # then return true otherwise false

In my above example, I want to see if children1 list value is there in children2 list, then return true.

1
  • You can just use the normal equals comparison. Commented Nov 23, 2013 at 6:27

2 Answers 2

4

sets have an issubset method, which is conveniently overloaded to <=:

def check_list(A, B):
    return set(A) <= set(B)

check_list(children1, children2) # True
check_list([1,4], [1,2,3]) # False
Sign up to request clarification or add additional context in comments.

Comments

1

You can use all

def check_list(child1, child2):
    child2 = set(child2)
    return all(child in child2 for child in child1)

children1 = ['test1']
children2 = ['test2', 'test5', 'test1']
print check_list(children1, children2)

Returns

True

2 Comments

If child2 is large it is much more efficient to convert it to a set.
@Tim Thanks Tim :) Included that in the answer :)