Reputation: 21
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
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 set
s
>>> len(set(ListA) & set(ListB)) > 0
True
Upvotes: 4
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