See https://docs.python.org/2/library/sets.html for documentation, and other URLs below for examples

In [1]:
X=set([1,2,3,4,5])
C=set(['Ithaca','Boston','Chicago'])
Stuff=set([1,'snow','Cornell','y'])
emptyset = set()
In [2]:
1 in X
Out[2]:
True
In [3]:
1 not in C
Out[3]:
True
In [4]:
def is_even(x): return(x%2 == 0)   #x%2 is the remainder after division by 2
In [5]:
is_even(4),is_even(21)
Out[5]:
(True, False)
In [6]:
len(X), len(C), len(Stuff), len(emptyset)  #cardinalities
Out[6]:
(5, 3, 4, 0)
In [7]:
Cp=set(['Ithaca','Chicago'])  #C' in notes
Xp=set(range(2,6))            #X' in notes
In [8]:
Xp
Out[8]:
{2, 3, 4, 5}
In [9]:
A=set([1,2,3])
In [10]:
X.isdisjoint(C), Cp.isdisjoint(C)
Out[10]:
(True, False)
In [11]:
Cp <= C, Cp.issubset(C)  #both mean 'is subset'
Out[11]:
(True, True)
In [12]:
C<=C, C<C  #test for proper and improper subsets
Out[12]:
(True, False)
In [13]:
Cp != C, Cp == C  #tests for set equality
Out[13]:
(True, False)
In [14]:
def powerset(S):
    R=[[]]
    for s in S: R += [T+[s] for T in R]
    return set(map(tuple,R))
In [15]:
powerset(A)
Out[15]:
{(), (1,), (1, 2), (1, 2, 3), (1, 3), (2,), (2, 3), (3,)}
In [16]:
sorted(powerset(A),key=len)  #subsets sorted by cardinality
Out[16]:
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
In [17]:
X | Stuff  # union
Out[17]:
{1, 2, 3, 4, 5, 'Cornell', 'snow', 'y'}
In [18]:
C | emptyset  #union
Out[18]:
{'Boston', 'Chicago', 'Ithaca'}
In [19]:
A | X  #union
Out[19]:
{1, 2, 3, 4, 5}
In [20]:
(A|X) == X, A.union(X) == X   #test whether A union X is equal to X
Out[20]:
(True, True)
In [21]:
X & Stuff # intersection
Out[21]:
{1}
In [22]:
X.intersection(Stuff)  #same thing
Out[22]:
{1}
In [23]:
C & emptyset
Out[23]:
set()
In [24]:
A & X
Out[24]:
{1, 2, 3}
In [25]:
X-Stuff  #set difference
Out[25]:
{2, 3, 4, 5}
In [26]:
C-emptyset
Out[26]:
{'Boston', 'Chicago', 'Ithaca'}
In [27]:
X^Stuff  #symmetric difference
Out[27]:
{2, 3, 4, 5, 'Cornell', 'snow', 'y'}
In [28]:
C^emptyset
Out[28]:
{'Boston', 'Chicago', 'Ithaca'}
In [29]:
X^A
Out[29]:
{4, 5}
In [30]:
A
Out[30]:
{1, 2, 3}
In [31]:
def cartesian_product(S1,S2): return {(a,b) for a in list(S1) for b in list(S2)}
In [32]:
cartesian_product(A,A)
Out[32]:
{(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)}
In [33]:
a = set('abracadabra')
b = set('alacazam')
a  # unique letters in a
Out[33]:
{'a', 'b', 'c', 'd', 'r'}
In [34]:
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
fruit = set(basket)
'orange' in fruit, 'crabgrass' in fruit
Out[34]:
(True, False)
In [35]:
{x for x in 'abracadabra' if x not in 'abc'}
Out[35]:
{'d', 'r'}
In [36]:
a-b # letters in a but not in b
Out[36]:
{'b', 'd', 'r'}
In [37]:
a|b  # letters in either a or b
Out[37]:
{'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}
In [38]:
a&b # letters in both a and b
Out[38]:
{'a', 'c'}
In [39]:
a^b # letters in a or b but not both
Out[39]:
{'b', 'd', 'l', 'm', 'r', 'z'}
In [ ]: