Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if one of the following items is in a list?

Tags:

python

People also ask

How do you check if an item exists in a list?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do you check if a set is in a list Python?

Python any() function checks if any Element of given Iterable is True. So, convert the list2 to Iterable and for each element in Iterable i.e. list2 check if any element exists in list1.


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


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

>>> a = [1,2,3,4]
>>> b = [2,7]
>>> any(x in a for x in b)
True

Maybe a bit more lazy:

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

print any((True for x in a if x in b))

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.


a = {2,3,4}
if {1,2} & a:
    pass

Code golf version. Consider using a set if it makes sense to do so. I find this more readable than a list comprehension.