CSE 160
Sets
Hannah Cheung
Announcements
2
Sets
�
3
1
2
3
3
2
1
Sets
�
4
3
1
4
3
1
4
1
5
5
Sets
�
5
1
2
3
3
2
1
Set Creation
6
s = set()
odd = {1, 3, 5}
prime = {2, 3, 5}
odd = set([1, 3, 5])
prime = set([2, 3, 5])
empty = set([]) # or set()
Set Operations
Iteration (but no indexing) over sets
7
odd = {1, 3, 5}
prime = {2, 3, 5}
4 in prime # membership
odd | prime # union
odd & prime # intersection
odd - prime # difference
for i in odd:
print(i)
Set Operations Practice
8
z = {5, 6, 7, 8}
y = {1, 2, 3, 1, 5}
k = z & y
j = z | y
m = y - z
n = z - y
Set Modification
9
Note: add remove, and discard all return None
Set Modification Practice
10
z = {5, 6, 7, 8}
y = {1, 2, 3, 1, 5}
p = z
q = set(z) # makes a copy of set z
z.add(9)
q = q | {35}
z.discard(7)
q = q – {6, 1, 8}
List vs Set Operations
11
out = []
for elem in list2:
if elem in list1:
out.append(elem)
set1 & set2
List vs Set Operations
12
out = list(list1)
for elem in list2:
if elem not in list1:
out.append(elem)
set1 | set2
List vs Set Operations
13
out = []
out2 = list1 + list2
for elem in out2:
if elem not in list1 or elem not in list2:
out.append(elem)
set1 ^ set2
Set Limitations
14