Sets and Mathematical Operations in Python

by kiawin

A description of matched sets mathematical operations in Python, taken from the Python Tutorial.

>>> # Demonstrate set operations on unique letters from two words
>>> # unique letters in a
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
set(['a', 'r', 'b', 'c', 'd'])
>>>
>>> # letters in a but not in b - difference
>>> a - b
set(['r', 'd', 'b'])
>>>
>>> # letters in either a or b - union
>>> a | b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>>
>>> # letters in both a and b - intersection
>>> a & b
set(['a', 'c'])
>>>
>>> # letters in a or b but not both - symmetric difference
>>> a ^ b
set(['r', 'd', 'b', 'm', 'z', 'l'])