Creating Sets
Use curly braces {} or the set() constructor. Note: {} creates an empty dict, not a set — use set() for an empty set.
# 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'>
Adding and Removing Elements
add(), remove(), discard(), pop(), and clear() modify sets in-place.
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)
Set Operations – Union, Intersection, Difference
Sets support mathematical operations. These are the most useful feature of sets.
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}
Fastest Way to Test Membership
Sets provide O(1) membership testing — far faster than lists for large collections.
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)
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
| Operation | Operator | Result |
|---|---|---|
| union | a | b | in either |
| intersection | a & b | in both |
| difference | a - b | in a, not b |
| symmetric diff | a ^ b | in 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:
- Create a set from a list that contains duplicates and confirm the duplicates are gone.
- Add and remove elements with
add()anddiscard(). - Given two sets of numbers, compute their union, intersection, and difference.
- Test membership with
inand 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, whileremove()raisesKeyError.- Set operations: union (
|), intersection (&), difference (-), symmetric difference (^). - Membership testing (
x in s) is O(1) on average thanks to hashing. - A
frozensetis 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()anddiscard()? - Why is membership testing faster in a set than in a list?
- What is a
frozenset?
Related Topics
FAQ
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.
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.
No. Set elements must be hashable, and lists are mutable and therefore unhashable. You can store tuples or frozensets instead, since those are immutable.
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.

