Sunday, April 26, 2009

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