MCS-201 · Unit 10

Data Structures and Control Statements in Python

Section 8 of 12

Block 3 · Unit 10Data Structures and Control Statements in Python9 min · Section 8 of 12

10.8Sets and Frozensets

Covers IGNOU MCS-201 §10.7.7, 10.8.4

A set holds each item at most once and answers “is this item present?” very quickly. Sets are used to remove duplicates, test membership and perform the mathematical set operations you know from discrete mathematics.

What a set is

  • Unordered: no indexing or slicing; the display order is not meaningful and can differ between runs.
  • Unique: duplicates are removed automatically.
  • Mutable: items can be added and removed (but the items themselves must be hashable).
  • An empty set is set(); {} creates an empty dictionary.

Set operations

With a = set('abrakadabra') = {a, b, d, k, r} and b = set('alexander') = {a, d, e, l, n, r, x}:

OperationOperatorMethodResult
Union (in either)a | ba.union(b){a, b, d, e, k, l, n, r, x}
Intersection (in both)a & ba.intersection(b){a, d, r}
Difference (in a only)a - ba.difference(b){b, k}
Symmetric difference (in exactly one)a ^ ba.symmetric_difference(b){b, e, k, l, n, x}
Subset / superseta <= b, a >= bissubset, issuperset
Disjoint (nothing in common)a.isdisjoint(b)False
A ∪ Beverything in A or B or both
A ∩ Bonly what is in both
A − Bin A but not in B
A △ Bin exactly one of them
The four set operations on A and B

Changing a set

MethodEffect
add(x)Add one item
update(iterable)Add many items
remove(x)Remove x; KeyError if absent
discard(x)Remove x if present; no error otherwise
pop()Remove and return an arbitrary item
clear()Remove all items
copy()Shallow copy

Frozensets

A frozenset is an immutable set: it supports all the non-changing operations (union, intersection, membership) but no add, remove or update. Because it is hashable, it can be an item of another set or a dictionary key.

Key takeaways

  • Sets hold unique hashable items, unordered, with fast in tests.
  • | union, & intersection, - difference, ^ symmetric difference.
  • add, update, remove, discard, pop, clear change a set.
  • frozenset is immutable and can be a key or a set item.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What does len({1, 2, 2, 3, 3, 3}) return?

Show answer

Answer: B. 3

Duplicates are removed, leaving {1, 2, 3}.

Question 2 · multiple choice

What does type({}) return?

Show answer

Answer: D. dict

Empty braces create an empty dictionary; an empty set must be written set().

Question 3 · multiple choice

What does this program print?

Python · quiz_sets.py
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a - b), sorted(a ^ b), len(a | b))
Show answer

Answer: A. [1, 2] [1, 2, 5] 5

a - b keeps 1 and 2; a ^ b keeps items in exactly one set (1, 2, 5); the union has five distinct items.

Question 4 · multiple choice

What happens with s = {"x"}; s.remove("y")?

Show answer

Answer: B. KeyError: 'y'

remove raises KeyError for a missing item; discard("y") would do nothing.

Question 5 · multiple choice

Why can a frozenset be a dictionary key but a set cannot?

Show answer

Answer: C. A frozenset is immutable and therefore hashable

Dictionary keys must be hashable, which requires that their value never changes.

Question 6 · short answer

Two lists hold the email addresses of users who visited a website on Monday and on Tuesday. Write statements that find the users who visited on both days, on Monday only, and the total number of different users.

Show worked answer

mon = set(monday_list), tue = set(tuesday_list). Both days: both = mon & tue. Monday only: mon_only = mon - tue. Total different users: len(mon | tue). Converting to sets removes repeated visits by the same user, and the set operators answer each question in one expression.

↑ ↓ move↵ openTab switch type