Showing posts with label intersection. Show all posts
Showing posts with label intersection. Show all posts

Saturday, May 16, 2009

The intersection of two Python lists using Set

Set is unordered unique collection of objects.

We can use Set to find the intersection of two lists/tuples.

Suppose that we have two lists.
>>> x = [1, 2, 3, 4, 5]
>>> y = [2, 6, 7, 3]

To find the intersection of the two lists, first change both x and y to the Set type, then use the intersection method (&).
>>> set(x) & set(y)
{2, 3}

If we need the output in list type, apply the list command, to the output.
>>> list(set(x) & set(y))
[2, 3]

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