Python Sets
Learn Python sets: create sets, add/remove items, use union, intersection, difference, symmetric difference, subset checks, and frozenset.
A Python set is an unordered collection of unique, hashable elements. Because sets enforce uniqueness automatically and support fast membership testing, they are ideal for deduplication, mathematical set algebra, and checking overlap between collections.
This chapter covers:
- How to create sets (literal syntax and
set()) - Adding and removing elements — and when each method raises an error
- The four set operations: union, intersection, difference, symmetric difference
- Operator shortcuts (
|,&,-,^) - Subset and superset tests
- Set comprehensions
- Frozen sets (
frozenset) for immutable, hashable sets
Creating Sets
Using curly braces
The quickest way to create a non-empty set is with a curly-brace literal. Each value appears only once, regardless of how many times you write it.
Define a set in Python
Using the set() constructor
Pass any iterable — a list, tuple, string, or range — to set() to build a set from it. Duplicate values are silently dropped.
Convert a list to a set in Python
Important: empty set
To create an empty set you must use set(). Writing {} creates an empty dictionary, not a set.
empty_set = set() # correct
empty_dict = {} # this is a dict!
print(type(empty_set)) # <class 'set'>
print(type(empty_dict)) # <class 'dict'>What can go inside a set?
A set element must be hashable — immutable types such as int, float, str, bool, and tuple work fine. Lists and other sets cannot be elements because they are mutable and therefore not hashable.
valid = {1, "hello", (2, 3), True} # OK
# invalid = {[1, 2]} # TypeError: unhashable type: 'list'
print(valid)Accessing Set Elements
Sets are unordered, so elements have no index and you cannot retrieve a single item by position. The standard way to visit every element is a for loop.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
# Output order may vary — sets are unorderedTo check whether a specific value exists, use the in operator:
colors = {"red", "green", "blue"}
print("red" in colors) # True
print("yellow" in colors) # FalseMembership testing on a set is O(1) on average — much faster than searching a list when collections are large.
For a dedicated chapter, see Access Set Items.
Adding Elements
Use add() to insert a single element, or update() to add multiple elements from any iterable.
Add an element to a set in Python
update() accepts any iterable and adds all its elements:
my_set = {1, 2, 3}
my_set.update([4, 5], {6, 7})
print(my_set) # {1, 2, 3, 4, 5, 6, 7}See Add Set Items for more detail.
Removing Elements
Python gives you several methods to remove elements, each with different behaviour when the element is missing.
| Method | Behaviour if element is absent |
|---|---|
remove(x) | Raises KeyError |
discard(x) | Does nothing (safe) |
pop() | Removes and returns an arbitrary element; raises KeyError if set is empty |
clear() | Removes all elements |
Remove an element from a set in Python
When to choose remove vs discard: use remove() when the element should be present and its absence signals a bug. Use discard() when the element might or might not be there and you simply want it gone.
See Remove Set Items for all removal methods.
Set Operations
Python sets implement the four classical set-algebra operations. Each operation is available both as a method and as an operator — choose whichever is clearer in context.
Set operations in Python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Union — all elements from both sets
print(set1.union(set2)) # {1, 2, 3, 4}
print(set1 | set2) # {1, 2, 3, 4}
# Intersection — only elements present in both
print(set1.intersection(set2)) # {2, 3}
print(set1 & set2) # {2, 3}
# Difference — elements in set1 but not set2
print(set1.difference(set2)) # {1}
print(set1 - set2) # {1}
# Symmetric difference — elements in either set, but not both
print(set1.symmetric_difference(set2)) # {1, 4}
print(set1 ^ set2) # {1, 4}Subset and superset checks
Use issubset(), issuperset(), or the comparison operators <= / >= to test containment relationships.
a = {1, 2}
b = {1, 2, 3, 4}
print(a.issubset(b)) # True — every element of a is in b
print(a <= b) # True
print(b.issuperset(a)) # True — b contains all elements of a
print(b >= a) # True
print(a < b) # True — proper subset (a != b)
print(a == b) # Falseisdisjoint() returns True when two sets share no elements at all:
x = {1, 2, 3}
y = {4, 5, 6}
print(x.isdisjoint(y)) # TrueSee Join Sets for in-place update variants such as |=, &=, -=, and ^=.
Set Comprehensions
Like list comprehensions, you can build a set with a compact expression using curly braces and a for clause.
squares = {x ** 2 for x in range(1, 6)}
print(squares) # {1, 4, 9, 16, 25}
# With a filter condition
even_squares = {x ** 2 for x in range(1, 11) if x % 2 == 0}
print(even_squares) # {4, 16, 36, 64, 100}Because the result is a set, duplicate values are automatically collapsed:
words = ["apple", "banana", "avocado", "blueberry"]
first_letters = {w[0] for w in words}
print(first_letters) # {'a', 'b'}Frozen Sets
A frozenset is an immutable version of a set. Once created, elements cannot be added or removed. Frozen sets are hashable, which means they can be used as dictionary keys or as elements of another set.
fs = frozenset([1, 2, 3])
print(fs) # frozenset({1, 2, 3})
# All read-only operations work
print(2 in fs) # True
print(fs | {4, 5}) # frozenset({1, 2, 3, 4, 5})
# fs.add(4) # AttributeError — frozenset has no add()
# Use as a dictionary key
permissions = {
frozenset(["read", "write"]): "editor",
frozenset(["read"]): "viewer",
}
user_perms = frozenset(["read", "write"])
print(permissions[user_perms]) # editorWhen to use frozenset: whenever you need a set-like object that must not change — as a constant configuration, a safe dictionary key, or when sharing a set across threads without locking.
Practical Examples
Remove duplicates from a list
Converting to a set and back is the simplest way to deduplicate a list. Note that the original order is not preserved; if order matters, use dict.fromkeys() instead.
Remove duplicates from a list using a set in Python
Check if two lists share any element
Check if two lists have any elements in common in Python using sets
isdisjoint() is a more direct alternative for this check:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(not set(list1).isdisjoint(set(list2))) # False — no common elementsFind unique tags across articles
article_a_tags = {"python", "tutorial", "beginner"}
article_b_tags = {"python", "advanced", "data-science"}
all_tags = article_a_tags | article_b_tags
shared_tags = article_a_tags & article_b_tags
only_in_a = article_a_tags - article_b_tags
print("All tags: ", all_tags)
print("Shared tags: ", shared_tags)
print("Only in A: ", only_in_a)Summary
| Operation | Method | Operator |
|---|---|---|
| Union | a.union(b) | a | b |
| Intersection | a.intersection(b) | a & b |
| Difference | a.difference(b) | a - b |
| Symmetric difference | a.symmetric_difference(b) | a ^ b |
| Subset test | a.issubset(b) | a <= b |
| Superset test | a.issuperset(b) | a >= b |
| Disjoint test | a.isdisjoint(b) | — |
Related chapters: Add Set Items · Remove Set Items · Access Set Items · Loop Sets · Join Sets · Set Methods