h1h1 h1h1 - 1 year ago 65
Python Question

Checking if all the elements in one list are also in another

I'm trying to compare two lists and simply print a message if the same value was found in both lists.

def listCompare():
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
if list1 in list2:
print("Number was found")
print("Number not in list")

This doesnt work, and I'm not sure of the simplest way to compare the two lists.

Answer Source

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