Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What are the common set operations in Python, and what is a frozenset?

SHORT ANSWER

Sets support union (|), intersection (&), difference (-) and symmetric difference (^). A set holds unique, hashable items with fast membership tests. A frozenset is an immutable set, so it can be a dict key or a set element.

Explain it simply

Two WhatsApp groups, "Class A" and "Class B". Union is everyone in either group. Intersection is people in both. Difference is people only in A. Symmetric difference is people in exactly one of them. A set never lists a person twice.

Example

python
a = {1, 2, 3, 4}
b = {3, 4, 5}

print(a | b)    # Output: {1, 2, 3, 4, 5}
print(a & b)    # Output: {3, 4}
print(a - b)    # Output: {1, 2}
print(a ^ b)    # Output: {1, 2, 5}
print(a.issubset({1, 2, 3, 4, 5}))   # Output: True

fs = frozenset([1, 2])
registry = {fs: "pair"}
print(registry[frozenset([2, 1])])   # Output: pair

Set membership (x in s) is O(1) on average, compared with O(n) for a list. Sets are unordered, so do not rely on printing order for larger or non-integer sets.

What to say in the interview

"Sets are unordered collections of unique hashable items. The main operations are union, intersection, difference and symmetric difference, available as operators and methods. Membership is average O(1). A frozenset is the immutable version, so it is hashable and can sit inside another set or be a dictionary key."

Common mistakes

  • Writing {} for an empty set; that is an empty dict.

#python#sets

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.