Python - Sets
Overview
Estimated time: 15–25 minutes
Use sets for fast membership tests and deduplication. Learn basic operations and typical patterns.
Learning Objectives
- Create sets and perform union, intersection, difference, symmetric difference.
- Use set comprehensions.
- Understand hashability and why elements must be immutable.
Prerequisites
Basics and operations
a = {1, 2, 3}
b = {3, 4}
print(2 in a)
print(a | b, a & b, a - b, a ^ b)
Deduplication
data = [1, 2, 2, 3]
print(list(set(data)))
Common Pitfalls
- Lists are unhashable; use tuples for compound members:
{(x, y)}
. - Set literals require braces; empty set is
set()
not{}
(that’s an empty dict).
Checks for Understanding
- How do you compute the intersection of two sets?
- Why can’t you put a list into a set?
Show answers
a & b
ora.intersection(b)
- Lists are mutable and unhashable; set elements must be hashable.
Exercises
- Given two lists, print common unique elements using sets.
- Use a set to check if a string has duplicate characters.