Python Forum

Full Version: Check if multiple values exist in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to find a way of testing whether or not at least one element from a list #1 is present in a list #2
One thing I've found is this thread: http://stackoverflow.com/questions/74028...-in-a-list though I dont' really understand the first(accepted) answer. If someone could break that answer down or suggest an alternative way of doing it, that would be a big help. 

It would look like:

mylist = [1,2,3,4]
mylist2 = [4,5,6]


if (any(mylist) in mylist2):
If the list values are uniques is better to use sets.
http://www.programiz.com/python-programming/set

for value in list1:
    if value in list2:
        print(value, "True")
   else:
       print(value, "False")
The SO answer is making sets from the lists. In Python a set is a collection without duplicate elements:
>>> set('abracadabra')
set(['a', 'r', 'b', 'c', 'd'])
These sets mimic the mathematical objects of the same name on which you can use the intersection operator to determine the elements that two sets have in common.
Why this code doesn't work?
print(value, "True") for value in list1 if value in list2
(Oct-06-2016, 07:20 PM)Ofnuts Wrote: [ -> ]The SO answer is making sets from the lists. In Python a set is a collection without duplicate elements:
>>> set('abracadabra')
set(['a', 'r', 'b', 'c', 'd'])
These sets mimic the mathematical objects of the same name on which you can use the intersection operator to determine the elements that two sets have in common.

Therefore, if you want to know whether sets (or lists, turned to sets) have any elements in common, you want to check if intersection of the sets is an empty set or not.
(Oct-06-2016, 07:28 PM)wavic Wrote: [ -> ]Why this code doesn't work?
print(value, "True") for value in list1 if value in list2
Because it is not valid python code

mylist = [1,2,3,4]
mylist2 = [4,5,6]
print([(value, "True") for value in mylist if value in mylist2])
Output:
[(4, 'True')]
Thanks for all of the answers guys. Good start for me here on the forum!