Advertisement
📦 Data Structures

Python Sets – Unique Collections with Set Operations

A set is an unordered collection of unique elements. Sets automatically eliminate duplicates, support mathematical set operations (union, intersection, difference), and provide O(1) membership testing — much faster than lists for checking if an item exists.

⏱️ 18 min read 🎯 Beginner 📅 Updated 2026

Creating Sets

Use curly braces {} or the set() constructor. Note: {} creates an empty dict, not a set — use set() for an empty set.

Python
# Creating sets
fruits = {"apple", "banana", "cherry", "apple"}  # Duplicate removed!
print(fruits)  # Order not guaranteed!

numbers = set([1, 2, 3, 2, 1])  # From list
print(numbers)  # {1, 2, 3}

empty_set = set()  # NOT {} (that's a dict!)
print(type(empty_set))  # <class 'set'>
▶ Output
{'cherry', 'banana', 'apple'} {1, 2, 3} <class 'set'>

Adding and Removing Elements

add(), remove(), discard(), pop(), and clear() modify sets in-place.

Python
s = {1, 2, 3}

s.add(4)          # Add single element
print(s)          # {1, 2, 3, 4}

s.remove(2)       # Remove - raises KeyError if not found
s.discard(99)     # Remove - no error if not found
print(s)          # {1, 3, 4}

popped = s.pop()  # Remove and return arbitrary element
print(popped)
▶ Output
{1, 2, 3, 4} {1, 3, 4} 1
Advertisement

Set Operations – Union, Intersection, Difference

Sets support mathematical operations. These are the most useful feature of sets.

Python
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)    # Union: all elements from both: {1,2,3,4,5,6,7,8}
print(a & b)    # Intersection: elements in BOTH: {4, 5}
print(a - b)    # Difference: in a but NOT b: {1, 2, 3}
print(a ^ b)    # Symmetric diff: in one but not both: {1,2,3,6,7,8}
▶ Output
{1, 2, 3, 4, 5, 6, 7, 8} {4, 5} {1, 2, 3} {1, 2, 3, 6, 7, 8}

Fastest Way to Test Membership

Sets provide O(1) membership testing — far faster than lists for large collections.

Python
import time

big_list = list(range(1000000))
big_set = set(range(1000000))

# Both find the same element, but set is ~100x faster
print(999999 in big_list)  # True (slow - O(n))
print(999999 in big_set)   # True (fast - O(1))

# Common use: remove duplicates from a list
duplicates = [1, 2, 3, 2, 4, 3, 5, 1]
unique = list(set(duplicates))
print(unique)
▶ Output
True True [1, 2, 3, 4, 5]

Sets: Instant Membership Tests and Math Operations

A set stores unique, unordered items with hash-based lookup. That gives two superpowers over lists: automatic de-duplication, and O(1) in checks (a list's in is O(n) — it scans).

seen = {2, 4, 6}
5 in seen          # near-instant, no scan
dedup = list(set([1, 1, 2, 3, 3]))   # → [1, 2, 3]

# 100x faster on big data than `x in some_list`
big = set(range(1_000_000))
999_999 in big     # O(1)

Set algebra

OperationOperatorResult
uniona | bin either
intersectiona & bin both
differencea - bin a, not b
symmetric diffa ^ bin exactly one

Two gotchas: sets are unordered — don't rely on insertion order. And elements must be hashable: you can put tuples in a set but not lists or dicts (unhashable type). Empty set is set(), not {} — that's an empty dict.

🏋️ Practical Exercise

Explore set behavior:

  1. Create a set from a list that contains duplicates and confirm the duplicates are gone.
  2. Add and remove elements with add() and discard().
  3. Given two sets of numbers, compute their union, intersection, and difference.
  4. Test membership with in and note that it is very fast.

🔥 Challenge Exercise

You have two lists: students enrolled in Math and students enrolled in Science. Using set operations, report who takes both subjects, who takes only one, and the total number of distinct students. Then deduplicate a list of email addresses while preserving uniqueness, and demonstrate that membership testing in a set is faster than in a list for large data.

📋 Summary

  • A set is an unordered collection of unique, hashable elements.
  • Creating a set from a list removes duplicates automatically.
  • add() inserts; discard() removes without error if missing, while remove() raises KeyError.
  • Set operations: union (|), intersection (&), difference (-), symmetric difference (^).
  • Membership testing (x in s) is O(1) on average thanks to hashing.
  • A frozenset is an immutable set that can be used as a dict key or set element.

Interview Questions on Sets

  • What is a set and how does it differ from a list?
  • Why are sets unordered and what are the implications?
  • How do you remove duplicates from a list using a set?
  • What are the main set operations (union, intersection, difference)?
  • What is the difference between remove() and discard()?
  • Why is membership testing faster in a set than in a list?
  • What is a frozenset?

FAQ

Why are sets unordered? +

Sets are implemented as hash tables, which store elements by hash value rather than insertion order. This is what makes membership testing O(1), but it means you cannot index a set or rely on its iteration order.

What is the difference between remove() and discard()? +

Both delete an element, but remove() raises a KeyError if the element is absent, while discard() does nothing. Use discard() when you are not sure the element exists.

Can a set contain a list? +

No. Set elements must be hashable, and lists are mutable and therefore unhashable. You can store tuples or frozensets instead, since those are immutable.

When should I use a set instead of a list? +

Use a set when you need uniqueness, fast membership tests, or mathematical set operations. Use a list when order matters or you need duplicate values and indexing.