70

Lets say I have a list a=[1,2,3] And I want to know if at least one of the numbers in it exist in another list, like this one: b=[4,5,6,7,8,1] In other words, I want to know if 1,2 or 3 exist(s) in list b. I now I could do something like

def func(a, b):
    for i in a:
       if i in b:
          return True
    return False

But is there possibly a way to put that in one line to make things tidy?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

6 Answers6

83

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

;)

Thomas
  • 174,939
  • 50
  • 355
  • 478
76

a simple one-liner would be:

any(i in b for i in a)
mata
  • 67,110
  • 10
  • 163
  • 162
66

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. :)

Danica
  • 28,423
  • 6
  • 90
  • 122
19

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)
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • @MattO'Brien the OP asks "I want to know if at least one of the numbers in it exist in another list" which logically reduces to a set problem. I'm intrigued by how in your example element a is not in the second list? It seems to be in it, _at least once_. I wonder if you are thinking about the count of elements which would be a `collections.Counter` problem – Davos Sep 25 '18 at 07:15
  • good point. I have no idea what I was thinking 2 years ago when I wrote that...I've deleted it... – tumultous_rooster Sep 27 '18 at 06:24
  • what is the right data type ? – FabioSpaghetti Jan 23 '19 at 13:07
  • @FabioSpaghetti The "set" datatype is more useful for this problem than a "list". – Raymond Hettinger Jan 30 '19 at 17:33
7

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
Maehler
  • 6,111
  • 1
  • 41
  • 46
5

This should work.

def func(a, b):
    return any([i in b for i in a])
rabbidrabbit
  • 420
  • 5
  • 13