Tuesday, October 15, 2013

Howto figure out whether two lists have any elements in common

While working with FragIt I had to figure out whether two lists had some elements in common (it does not matter which!) and I came up with the following piece of code (with the help of Google and Stack Overflow of course)

def shares_elements(a, b):
"""Returns True if lists (sets) a and b shares elements. Otherwise false.
"""
sa = set(a)
sb = set(b)
return len(sa & sb) > 0
It takes advantage of the highly underused Sets available in python on which we can do some neat mathematically sane operations. I guess people just go for Lists and work their magic on that.