Python · The language, not just syntax

How do sets work and when are they the right tool?

EasysetshashingmembershipUpdated Oct 2026
Quiz this track

Short answer

A set is an unordered collection of unique hashable elements with average O(1) membership tests and set algebra such as union, intersection and difference. Use it for deduplication and fast membership checks.

Sets use a hash table similar to a dict but store only keys. Membership, insertion and deletion are O(1) on average, which makes a set the right structure when the question is whether an element is present rather than where it is.

python
allowed = {"admin", "editor", "viewer"}
requested = {"editor", "guest"}

print("admin" in allowed)
print(requested & allowed)
print(requested - allowed)
print(allowed | requested)
Intersection gives shared roles, difference gives unknown roles, and union combines them.

Where sets help

  • Deduplicating a list while preserving no particular order
  • Fast membership checks in loops instead of scanning a list
  • Comparing collections with intersection and difference
  • Tracking visited nodes in graph algorithms

Sets require hashable elements, so you cannot put a list or dict inside one. Iteration order is not guaranteed and should never be relied on for output. When you need an immutable, hashable set, use frozenset, which can itself be a dict key or an element of another set.

Set order can look stable within a single run for small integers, but that is an implementation detail. Sort explicitly when order matters.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between a set and a frozenset?
  2. 2When is a set faster than a list, and when is it slower?
  3. 3How do you deduplicate a list while preserving order?
  4. 4Why can't a list be stored in a set?

Say it in the interview

A set is a hash-based collection of unique, hashable elements. Membership is O(1) on average, which is the main reason I reach for it, along with union, intersection and difference for comparisons. I use frozenset when I need an immutable, hashable set. I never depend on iteration order, and I sort explicitly if output order matters.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.