Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one-liner to check if at least one item in list exists in another list? [duplicate]

Tags:

python

People also ask

How do you check if an item in one list is in another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you see if an item in a list is in another list Python?

To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.


Python 2.6 and above:

def func(a, b):
  return not set(a).isdisjoint(b)

For 2.4 or 2.5:

def func(a, b):
  return len(set(a).intersection(b)) != 0

For 2.3 and below:

sudo apt-get update
sudo apt-get upgrade

;)


a simple one-liner would be:

any(i in b for i in a)

There are many ways to do this. The most direct translation is:

any_in = lambda a, b: any(i in b for i in a)

You could also use various things involving sets, such as:

any_in = lambda a, b: bool(set(a).intersection(b))

(which depends on the elements of a being hashable, but if that's true, it'll probably be faster to make a set of the larger out of a and b for either of these approaches).

Edit: isdisjoint is better than intersection for Python 2.6 and above, as noted by various people below. Glad to learn about that. :)


This is a set problem, not a list problem. With the right data type, the answer is often immediately obvious :-)

def func(a, b):
    return not set(a).isdisjoint(b)

By converting your lists to sets you can perform set operations on them. If the intersection is larger than 0, you have at least one element matching:

len(set(a) & set(b)) > 0