Menu Close

How to test if lists share any items in Python?

Sometimes, we want to test if lists share any items in Python.

In this article, we’ll look at how to test if lists share any items in Python.

How to test if lists share any items in Python?

To test if lists share any items in Python, we can use the & operator after converting the lists to sets.

For instance, we write

bool(set(a) & set(b))

to converts lists a and b to sets with set.

Then we use the & operator to get the intersection of the sets.

And then we call bool to check if the intersection is empty or not.

Conclusion

To test if lists share any items in Python, we can use the & operator after converting the lists to sets.

Posted in Python, Python Answers