Python Forum
Check if multiple values exist in a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Check if multiple values exist in a list (/thread-354.html)



Check if multiple values exist in a list - glidecode - Oct-06-2016

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/740287/how-to-check-if-one-of-the-following-items-is-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):


RE: Check if multiple values exist in a list - wavic - Oct-06-2016

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")



RE: Check if multiple values exist in a list - Ofnuts - Oct-06-2016

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.


RE: Check if multiple values exist in a list - wavic - Oct-06-2016

Why this code doesn't work?
print(value, "True") for value in list1 if value in list2



RE: Check if multiple values exist in a list - j.crater - Oct-06-2016

(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.


RE: Check if multiple values exist in a list - Yoriz - Oct-06-2016

(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')]



RE: Check if multiple values exist in a list - glidecode - Oct-06-2016

Thanks for all of the answers guys. Good start for me here on the forum!