Skip to content
Advertisement

Test if any values in list are in other list

I have a List, L, and some Values, V. If none of them are in the List it passes the condition. As for the other side, if one of them it’s in the list it passes the other condition.

The code should be something like this

If "none elements of" V in L:
    print("OK")
If "one element of" V in L:
    print("Not OK")

For example I have the following list:

L= [(3, 0), (3, 2), (3, 4)]

And I want to check with the values in the array v, for example:

V = [0,1]

With this V and this L it should print “Not OK” because 0 is in the list. If V was something like V = [1,5] it should print “OK” because none of the elements of V are in the list L

I have tried the any(x in V for x in L), the [(x in L) for x in V] and the [x for x in V if x in L] and canĀ“t make any work (it always gives me “Not OK”).

Also I would like to said that I would be working with big arrays (Len(V) and Len(L) while be very big) so I would also like the most optmized way to do it

Advertisement

Answer

You can use np.isin(). This function will return True for any value of V that is in L. Then sum the result as follows:

import numpy as np

if np.isin(L, V).sum()>0:
    print ('Not OK')
else:
    print('OK')
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement