As the title suggests, there may be occasions when you want to check if one of the elements in one list is in another. In my case, I needed it when solving the CheckiO problem, but I think I will have the opportunity to use it in practice.
When I searched for what happened, [This Stack Overflow article](http://stackoverflow.com/questions/10668282/one-liner-to-check-if-at-least-one-item-in-list -exists-in-another-list) I will introduce the method because it was organized.
The goal is to create a function that has one list a and another list b, and returns True if one of the elements in list a is in list b, False if it doesn't.
a = ['A', 'B']
b = ['B', 'C', 'D']
True because'B' in list a exists in list b
a = ['A', 'B']
b = ['C', 'D', 'E']
False because neither'A'and'B' in list a are in list b
def func1(a, b):
return any(i in b for i in a)
This is a method using any () and a generator expression. Use for i in a
to extract the elements i one by one, and use ʻi in b` to check if the element i exists in b. Since it uses a generator, it returns True when it knows it exists.
def func2(a, b):
len(set(a) & set(b)) != 0
This is a method of converting a and b into a set and checking if they have an intersection. It's pretty easy to read.
def func3(a, b):
return not set(a).isdisjoint(b)
Use isdisjoint (), which is the opposite of method 2 and returns True if it has no intersection. Personally, I don't like not.
So far, I've summarized how to check if one of the elements in one list is in another.
I haven't compared the performance, but I think it's a good idea to choose the one that suits you while considering readability.
python - one-liner to check if at least one item in list exists in another list? - Stack Overflow
Recommended Posts