Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether an item in a list exist in another list or not python

Tags:

python

There are 2 list

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

Now I want to check whether an element from a exist in b or not in python one-liner.

I can use loop on a and then check if it exist in b or not. But I want something pythonic way (one-liner).

like image 950
PythonEnthusiast Avatar asked Jan 11 '23 19:01

PythonEnthusiast


1 Answers

bool(set(a)&set(b)) converts a and b into sets and then applies the intersection operator (&) on them. Then bool is applied on the resulting set, which returns False if the set is empty (no element is common), otherwise True (the set is non-empty and has the common element(s)).

Without using sets: any(True for x in a if x in b). any() returns True if any one of the elements is true, otherwise False.

like image 94
Ramchandra Apte Avatar answered Feb 23 '23 03:02

Ramchandra Apte