The intersection of two Python lists

Suppose that you have two lists, x and y. You can list out the items that are common to the two lists.

>>> x = [1,2,3,4,5]
>>> y = [2,6,7,3]
>>> [i for i in y if i in x]
[2, 3]

To see how many items found in the intersection.

>>> len([i for i in y if i in x])
2

Related

This entry was posted in Python and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>