Python — Sets
Creating sets
Sets are unordered collections of unique elements:
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
mixed = {1, "hello", 3.14}
Empty set — use set(), not {}:
empty = set() # empty set
not_a_set = {} # this is an empty dictionary!
Automatic deduplication
Sets remove duplicates automatically:
numbers = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
print(numbers) # {1, 2, 3, 4}
# Remove duplicates from a list
names = ["Ada", "Grace", "Ada", "Linus", "Grace"]
unique_names = set(names)
print(unique_names) # {'Ada', 'Grace', 'Linus'}
# Back to a list (order may change)
unique_list = list(unique_names)
Adding and removing elements
fruits = {"apple", "banana"}
# add — single element
fruits.add("cherry")
print(fruits) # {'apple', 'banana', 'cherry'}
# update — add multiple elements
fruits.update(["grape", "kiwi"])
print(fruits) # {'apple', 'banana', 'cherry', 'grape', 'kiwi'}
# remove — raises KeyError if not found
fruits.remove("banana")
# discard — no error if not found
fruits.discard("mango") # no error
# pop — remove and return an arbitrary element
element = fruits.pop()
# clear — empty the set
fruits.clear()
Set operations
Sets support mathematical operations — union, intersection, difference:
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
# Union — all elements from both sets
print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8}
print(a.union(b)) # same thing
# Intersection — elements in both sets
print(a & b) # {4, 5}
print(a.intersection(b))
# Difference — elements in a but not in b
print(a - b) # {1, 2, 3}
print(a.difference(b))
# Symmetric difference — elements in either but not both
print(a ^ b) # {1, 2, 3, 6, 7, 8}
print(a.symmetric_difference(b))
Subset and superset
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
c = {1, 2}
# a is a subset of b (all elements of a are in b)
print(a <= b) # True
print(a.issubset(b))
# b is a superset of a
print(b >= a) # True
print(b.issuperset(a))
# c is a subset of a
print(c <= a) # True
# Strict subset (a is subset but not equal)
print(a < b) # True
print(a < a) # False — equal, not strict subset
Frozen sets — immutable sets
fs = frozenset([1, 2, 3])
# fs.add(4) # AttributeError: 'frozenset' has no attribute 'add'
# Can be used as dictionary keys
d = {frozenset([1, 2]): "pair"}
Frozen sets can be dictionary keys and elements of other sets. Regular sets can't.
Set comprehensions
# Create a set of squares
squares = {x ** 2 for x in range(-5, 6)}
print(squares) # {0, 1, 4, 9, 16, 25}
# Filter with condition
evens = {x for x in range(20) if x % 2 == 0}
print(evens) # {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
When to use sets
Use sets when:
- You need to check membership quickly (
x in setis O(1)) - You need unique elements
- You need set operations (union, intersection, difference)
- You want to remove duplicates from a list
Don't use sets when:
- You need to maintain order (use lists)
- You need duplicate counts (use
Counter) - You need to access elements by index (use lists)
Performance comparison
import time
# Membership test performance
large_list = list(range(1000000))
large_set = set(range(1000000))
# List — O(n) — slow
start = time.time()
999999 in large_list
list_time = time.time() - start
# Set — O(1) — fast
start = time.time()
999999 in large_set
set_time = time.time() - start
print(f"List: {list_time:.6f}s")
print(f"Set: {set_time:.6f}s")
Sets use hash tables for O(1) membership checks. Lists scan every element for O(n).
Common patterns
# Find common elements between two lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = list(set(list1) & set(list2))
print(common) # [4, 5]
# Check if all elements of one list are in another
required = {"python", "sql", "git"}
applicant_skills = {"python", "sql", "git", "docker"}
print(required.issubset(applicant_skills)) # True — has all required skills
# Remove duplicates preserving approximate order
seen = set()
unique_ordered = []
for item in [1, 2, 2, 3, 1, 4, 3]:
if item not in seen:
seen.add(item)
unique_ordered.append(item)
print(unique_ordered) # [1, 2, 3, 4]
# Symmetric difference for items in one list but not both
a = {"apple", "banana", "cherry"}
b = {"banana", "cherry", "date"}
exclusive = a ^ b # {"apple", "date"}
Mini Practice
- Create a set from a list with duplicates and print the unique elements
- Find the intersection of two sets representing student enrollments
- Use set operations to find students enrolled in both Math and Science
- Create a set comprehension that generates all prime numbers up to 50
- Check if one set is a subset of another
Next: dictionaries — key-value pairs →
Related Topics
Frequently Asked Questions about Sets
What is Sets in Python?
Sets is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sets?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sets.
Why is Sets important in Python?
Sets is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.