The intersection of two Python lists using Set

Friday, May 15th, 2009
Advertisement

Subscribe.
Enter your email:

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]
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

One Response to “The intersection of two Python lists using Set”

Leave a Reply

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