Tuesday, 29 November 2011

Find the Union and Intersection of two lists in python

Here are three functions using sets to remove duplicate entries from a list, find the intersection of two lists, and find the union of two lists. Note, sets were introduced in Python 2.4, so Python 2.4 or later is required.
def unique(a):
    """ return the list with duplicate elements removed """
    return list(set(a))

def intersect(a, b):
    """ return the intersection of two lists """
    return list(set(a) & set(b))

def union(a, b):
    """ return the union of two lists """
    return list(set(a) | set(b))

if __name__ == "__main__":
    a = [1,2,3,4,3,2,1,0,9,8,7,6,5,4,3,1]
    b = [19,18,17,12,1,4,5,6,13,14,15,13,16,20]
    print unique(a)
    print unique(b)
    print intersect(a, b)
    print union(a, b)

Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 4, 5, 6, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[1, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20] 

For more information on Python sets, see the Library Reference.


No comments:

Post a Comment