Saturday 5 December 2015

Python: Find intersection and union of lists

Following program finds
a.   Unique elements in list
b.   Intersection of two lists
c.    Union of two lists.

test.py
def unique(a):
    return list(set(a))

def intersect(a, b):
    return list(set(a) & set(b))

def union(a, b):
    return list(set(a) | set(b))

if __name__ == "__main__": 
    a = [2, 4, 6, 8, 10, 10, 8, 6]
    b = [2, 4, 8, 16, 1, 3, 5, 2, 4]
    print(unique(a))
    print(intersect(a, b))
    print(union(a, b))

$ python3 test.py
[8, 2, 10, 4, 6]
[8, 2, 4]
[1, 2, 3, 4, 5, 6, 8, 10, 16]


Previous                                                 Next                                                 Home

No comments:

Post a Comment