Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 9, 2012

Python set operations

First let's take a look at the definition of set. A set is a unordered collection of elements with no duplicates. We can perform a few interesting operations on sets.
numbers1 = set([1,3,5,7,9])
numbers2 = set([3,5,8,10])

#union contains all elements from both sets
union = numbers1 | numbers2
#intersection contains elements contained in both sets
intersection = numbers1 & numbers2
#difference contains elements that are in set1 but not in set2
difference = numbers1 - numbers2
#symmetric difference contains all elements that are in set1 and set2 but not in both
#which would be the same as union minus intersection
symmetric_difference = numbers1 ^ numbers2

print union
print intersection
print difference
print symmetric_difference 

set([1, 3, 5, 7, 8, 9, 10])
set([3, 5])
set([1, 7, 9])
set([1, 7, 8, 9, 10])

No comments:

Post a Comment