Python Tip #1: Intersection of two lists

This will be the first of what I’m going to try to be a daily series of small tips and tricks in Python.

We have two lists:

A = [1, 2, 3, 4, 5, 6]  and  B = [10, 9, 8, 7, 6, 5]

To get the elements that are in both lists:

def intersect(*lists):

    return reduce(set.intersection, lists)

The only trick is to actually pass the lists to the function not as lists but as sets. [EDIT: This can be done before the function call or just change the function to what Paddy wrote on the 1st comment] Bad part: if the lists contain duplicate elements, there they go. Sets only contain unique items. Which, by the way, leads to another question “What if I want to eliminate duplicates from a list?”:

newlist = set(oldlist)

3 thoughts on “Python Tip #1: Intersection of two lists

  1. Podes sempre usar apenas:
    >>> intersect = lambda *lists: reduce(lambda x,y: set.intersection(set(x),set(y)), lists)
    >>> intersect([1,2,3,7,8,9], [2,4,6,8], [8,9,10,11])

    Usei o lambda no reduce para evitar percorrer o lists 2 vezes (ou seja, não usar nem listas por compreensão ou um map por causa do set()).

  2. Your intersect function has errors.

    >>> a=[1,2,3,4,5,6]; b=[10,9,8,7,6,5]
    >>> def intersect(*lists):
    return list(reduce(set.intersection, (set(l) for l in lists)))

    >>> intersect(a,b)
    [5, 6]
    >>> c=[2,4,6,8]
    >>> intersect(a,b,c)

    – Paddy.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s