tags:

views:

3471

answers:

7

I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.

>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True
+3  A: 

Think about what the code actually says!

>>> (1 or 2)
1
>>> (2 or 1)
2

That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:

def or(x, y):
    if x: return x
    if y: return y
    return False

In the first example, x == 1 and y == 2. In the second example, it's vice versa. That's why it returns different values depending on the order of them.

Deniz Dogan
+5  A: 
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]


>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])

Both empty lists and empty sets are False, so you can use the value directly as a truth value.

Joe Koberg
The intersection idea gave me this idea.return len(set(a).intersection(set(b)))
Deon
A: 

Best I could come up with:

any([True for e in (1, 2) if e in a])
Bastien Léonard
+2  A: 

This will do it in one line.

>>> a=[2,3,4]
>>> b=[1,2]
>>> bool(sum(map(lambda x: x in b, a)))
True
Chris Upchurch
I'm not getting a True here >>> print a [2, 3, 4] >>> print b [2, 7] >>> reduce(lambda x, y: x in b, a) False
Deon
Yep. You're right. reduce() wasn't quite handling boolean values the way I thought it would. The revised version I wrote above works for that case though.
Chris Upchurch
A: 

In some cases (e.g. unique list elements), set operations can be used.

>>> a=[2,3,4]
>>> set(a) - set([2,3]) != set(a)
True
>>>

Or, using set.isdisjoint(),

>>> not set(a).isdisjoint(set([2,3]))
True
>>> not set(a).isdisjoint(set([5,6]))
False
>>>
gimel
A: 

Maybe a bit more lazy:

a = [1,2,3,4]
b = [2,7]

print any((True for x in a if x in b))
It's nearly the same as the one I posted.
Bastien Léonard
+5  A: 

Ah, Tobias you beat me to it. I was thinking of this slight variation on your solution:

print any(x in a for x in b)
emallama