Checking if any elements in one list are in another [duplicate]

You could solve this many ways. One that is pretty simple to understand is to just use a loop.

def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False

A more compact way you can do it is to use map and reduce:

reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))

Even better, the reduce can be replaced with any:

any(map(lambda v: v in list2, list1))

You could also use sets:

len(set(list1).intersection(list2)) > 0

Leave a Comment