hojoo235
hojoo235

Reputation: 21

Check for partial match between 2 lists

I want to check if there is any similar elements between two lists.

For example:

ListA = ['A', 'B', 'C', 'D']
ListB = ['X', 'A', 'Y', 'Z']

I tried any(ListB) in ListA but that returns False

Is it possible to do something like this? I'm completely new to this language.

Upvotes: 1

Views: 995

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52071

any needs an iterable of True and False values.

>>> ListA = ['A', 'B', 'C', 'D']
>>> ListB = ['X', 'A', 'Y', 'Z']
>>> any(i in ListB for i in ListA)
True

Here you are testing if there is any value of ListB in ListA.


A better way as mentioned in the comments is to use sets

>>> len(set(ListA) & set(ListB)) > 0
True

Upvotes: 4

Paulo Scardine
Paulo Scardine

Reputation: 77251

Use sets instead of lists:

>>> list_a = {'A', 'B', 'C', 'D'}
>>> list_b = {'X', 'A', 'Y', 'Z'}
>>> list_a.intersection(list_b)
{'A'}

Upvotes: 1

Related Questions