Sets and Tuples
Winter 2025
1
Adrian Salguero
Announcements
2
Sets
3
Creating a Set
4
Set Operations
5
Mathematical Operation | In Python | Example |
Membership | in | 4 in prime → False |
Union | | | odd | prime → {1, 2, 3, 5} |
Intersection | & | odd & prime → {3, 5} |
Difference | - | odd - prime → {1} |
Symmetric difference | ^ | odd ^ prime → {1, 2} |
odd = {1, 3, 5}
prime = {2, 3, 5}
Set Iterations
for item in myset:
# do something with item
6
Modifying Sets
7
Practice with Sets
z = {5, 6, 7, 8}
y = {1, 2, 3, 1, 5}
k = z & y
j = z | y
m = y - z
n = z - y
8
More Practice with Sets
z = {5, 6, 7, 8}
y = {1, 2, 3, 1, 5}
k = z.intersection(y)
j = z.union(y)
m = y.difference(z)
n = z.difference(y)
9
Even More Practice with Sets
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}
10
List vs. Set Operations
Suppose we have two lists, list1 and list2, and we want to find the common elements in the lists.
out1 = []
for elem in list2:
if elem in list1:
out1.append(elem)
-----------------------------------------------------------------
Suppose we have two sets, set1 and set2, and we want to find the common elements in the sets.
set1 & set2
11
List vs. Set Operations (cont.)
Find elements in either list1 or list2 (or both) (without duplicates)
out2 = list(list1) # make a copy
for elem in list2:
if elem not in out2: # don’t append elements already in out2
out2.append(elem)
Another way:
out2 = list1 + list2 # if an item is in BOTH lists, it will appear TWICE!
for elem in out1: # out1 = common elements in both lists
out2.remove(elem) # Remove common elements, leaving just a single copy
-----------------------------------------------------------------
Find the elements in either set1 or set2 (or both)
set1 | set2
12
List vs Set Operations (cont.)
Find the elements in either list but not in both
out3 = []
out2 = list1 + list2 # if an item is in BOTH lists, it will appear TWICE!
for elem in out2:
if elem not in list1 or elem not in list2:
out3.append(elem)
-----------------------------------------------------------------
Find the elements in either set but not in both:
set1 ^ set2
13
Mutable vs. Immutable
14
Tuples
Examples:
()
(4, 7, 9)
("hi", [1, 2], 5)
15
Tuple operations
("Once", "upon", "a", "time", "there", "was", "a")
(3, 1) + (4, 1) => (3, 1, 4, 1) # creates a new tuple!
tup = ("Once", "upon", "a", "time", "there", "was", "a")
print(tup[0]) => "Once"
print(tup[-1]) => "a"
16
Tuple operations
17
("Once", "upon", "a", "time", "there", "was", "a")
(3, 1) + (4, 1) => (3, 1, 4, 1) # a new tuple!
tup = ("Once", "upon", "a", "time", "there", "was", "a")
print(tup[0]) => "Once"
print(tup[-1]) => "a"
Tuples are immutable�Lists are mutable
18
def update_record(record, position, value):
"""Change the value at the given position"""
record[position] = value
mylist = [1, 2, 3]
mytuple = (1, 2, 3)
update_record(mylist, 1, 10)
print(mylist)
update_record(mytuple, 1, 10)
print(mytuple)