user2467545
user2467545

Reputation:

How to compare two lists in Python efficiently?

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.

Upvotes: 0

Views: 468

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

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

Upvotes: 1

Free Monica Cellio
Free Monica Cellio

Reputation: 2290

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

Upvotes: 4

Related Questions