38

I'm trying to compare two lists and simply print a message if any value from the first list is in the second list.

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

In this example, I want the if to evaluate to True because 5 is in both lists. This doesn't work, and I'm not sure of the simplest way to compare the two lists.

David Alber
  • 17,624
  • 6
  • 65
  • 71
h1h1
  • 730
  • 4
  • 11
  • 19
  • 2
    I have taken two actions on this question: I modified the question to clarify what is the evident original point of the question: determine if any value in one list is in another list. I believe this is the original intent given the the top answers on the question address that and @h1h1 selected an answer that addresses that. h1h1 hasn't been around for years, so I could not ask him or her to clarify. The second action taken was to revert the accepted answer to its state before it was partway modified to address "determine if all elements in one list are in a second list". – David Alber Feb 03 '17 at 17:18
  • 1
    Does this answer your question? [How to check if one of the following items is in a list?](https://stackoverflow.com/questions/740287/how-to-check-if-one-of-the-following-items-is-in-a-list) – user202729 Dec 05 '21 at 18:01

7 Answers7

78

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
David Alber
  • 17,624
  • 6
  • 65
  • 71
  • 4
    the first version doesn't work (when just one value is in both lists, you get True not only when all values are in both lists) – thias Aug 16 '13 at 11:49
  • 2
    the first approach is wrong. It is comparing from list1 towards list2. A loop based comparison must be performed from both perspectives, including from list2 towards list1. For example: for val in list2:... if val in list1... etc. Also, you are returning True if the very first value is found on list2, which means it will not proceed to compare all values. The inner if statement should be (if val not in list2: return False), which means it would continue as far as there are correct values from the first to the last element. – gextra Jan 26 '14 at 14:41
  • 2
    @gextra: The question was, as interpreted by everyone who answered, to return `True` if any value in `list1` is in `list2` or vice versa. Your comment -- and the one before it -- implies you believe the question is to determine if the lists contain all identical values (or maybe determine if the values in `list1` are a subset of the values in `list2`; I can't tell for certain for both comments). I can see how you could interpret the question that way, but do not think that was the intent. You could ask for clarification on the question so that we know for certain. – David Alber Jan 26 '14 at 19:32
  • @David The `or` should be `and` I believe: reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1)) – Ankur Agarwal May 02 '15 at 00:11
  • 1
    This answer has been edited several times to look fairly different from its original form, and it no longer answers the original question. Also, the title of the question has been edited to make it a different question than was originally asked. The original question by @h1h1, as interpreted by most who answered it, was to identify if one list contains any of the same elements of another list. The question has been changed to check if one list contains all elements of a second list. This answer has been partially modified to answer that, but other parts still answer the original question. – David Alber Feb 03 '17 at 08:53
  • 2
    Similar to my comment on the question: I have taken two actions on this question: I modified it to reflect the evident original point of the question: determine if any value in one list is in another list. I believe this is the original intent given the the top answers on the question address that and @h1h1 selected an answer that addresses that. h1h1 hasn't been around for years, so I could not ask him or her to clarify. The second action taken was to revert this answer to its state before it was partway modified to address "determine if all elements in one list are in a second list". – David Alber Feb 03 '17 at 17:20
16

There are different ways. If you just want to check if one list contains any element from the other list, you can do this..

not set(list1).isdisjoint(list2)

I believe using isdisjoint is better than intersection for Python 2.6 and above.

vidit
  • 6,293
  • 3
  • 32
  • 50
9

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")
dansalmo
  • 11,506
  • 5
  • 58
  • 53
9

There is a built in function to compare lists:

Following is the syntax for cmp() method −

cmp(list1, list2)

#!/usr/bin/python

list1, list2 = [123, 'xyz'], [123, 'xyz']

print cmp(list1,list2)

When we run above program, it produces following result −

0

If the result is a tie, meaning that 0 is returned

Hrqls
  • 2,944
  • 4
  • 34
  • 54
user1463110
  • 175
  • 1
  • 8
  • 2
    This does not answer the question. OP wants to know if the same value was found in both lists. – Martin May 12 '15 at 07:54
7

You could change the lists to sets and then compare both sets using the & function. eg:

list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]

if set(list1) & set(list2):
    print "Number was found"
else:
    print "Number not in list"

The "&" operator gives the intersection point between the two sets. If there is an intersection, a set with the intersecting points will be returned. If there is no intersecting points then an empty set will be returned.

When you evaluate an empty set/list/dict/tuple with the "if" operator in Python the boolean False is returned.

colins44
  • 544
  • 6
  • 9
1

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Aman Madan
  • 93
  • 5
0

What if I want to to return the list of occurrence of the values in list1 as compared to list2 as below

list1 = [1, 2, 3, 4, 5]

list2 = [5, 6, 7, 8, 9]

I expect to 0 occurrence of 1 ,0 occurrence of 2, 0 occurrence of 3, 0 occurrence of 4, and 1 occurrence of 5 to have a new list as below,

new_list=[0,0,0,0,1]
marmeladze
  • 6,468
  • 3
  • 24
  • 45