Skip to the solution
EasyDSA8 min read

What set operations does Python support?

545 views

The problem

Question presented to candidate: "What operations does a Python set support? Show me how you would find what two collections have in common, what is missing from one of them, and explain when a set is the right data structure in the first place."

What a strong answer should cover:

  • A set is an unordered collection of unique, hashable items backed by a hash table, so x in s is O(1) on average versus O(n) for a list.
  • The four operations with their operators and methods: union |, intersection &, difference -, symmetric difference ^; the methods accept any iterable (and several of them), the operators need sets.
  • Comparisons are containment tests: <= subset, < proper subset, >=/> superset, isdisjoint β€” sets are only partially ordered, so a < b and b < a can both be False.
  • In-place forms (|=, &=, -=, ^=, update, intersection_update, ...) and single-item add, remove (raises KeyError) versus discard (silent).
  • frozenset is the immutable, hashable variant (usable as a dict key or set element); {} is an empty dict; 1, 1.0 and True count as one element; dedup with set() loses order, dict.fromkeys keeps it.

Code / implementation expected: Yes β€” a short snippet comparing two collections (common, missing, extra items).

  • set

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonUnion, intersection, difference, comparisons and in-place updates
PythonDedup, comparing collections, frozenset and the common gotchas

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 21 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What are f-strings?

Continue