Tutorials Python Python Sets
Ch 21 / 58
Python Beginner 10 min read Chapter 21 of 58

Python Sets

A set is Python's unordered collection of unique elements — perfect for removing duplicates, fast membership testing, and mathematical set operations. Sets are the secret weapon for tasks like finding common items between two lists, or items that appear in one list but not another. This chapter covers creating sets, adding and removing elements, all four set operations with Venn diagrams, the full method reference, and immutable frozensets.

What you'll learn in this chapter
Creating sets and set properties
Adding and removing elements
Set operations: union, intersection, difference
Symmetric difference and subset/superset tests
All set methods with examples
Frozen sets — immutable sets
Advertisement

Creating Sets

A set is an unordered collection of unique, immutable elements enclosed in curly braces {}. Sets automatically remove duplicates — if you insert the same value twice, it appears only once. Sets are mutable (you can add/remove elements), but the elements themselves must be hashable (immutable).

Empty set — use set(), not {} {} creates an empty dict, not a set! Always use set() to create an empty set.
Unique
No duplicate values
Unordered
No index, no position
Mutable
Add/remove elements
O(1) lookup
Hash-table backed
Python — creating_sets.py
# Create a set with curly braces
fruits  = {"apple", "banana", "cherry"}

# Duplicates removed automatically
nums    = {1, 2, 2, 3, 3, 3, 4}
print(nums)              # {1, 2, 3, 4}  — order may vary

# ⚠️ Empty set — MUST use set(), NOT {}
empty_set  = set()       # correct
empty_dict = {}           # this is a dict!
print(type(empty_set))   # <class 'set'>
print(type(empty_dict))  # <class 'dict'>

# Create from list — removes duplicates
letters = set(["a", "b", "a", "c", "b"])
print(letters)           # {'a', 'b', 'c'}

# Create from string
chars = set("python")
print(chars)             # {'p','y','t','h','o','n'}

# Set properties
print(len(fruits))       # 3
print("apple" in fruits)  # True  — O(1) lookup!
print("grape" in fruits)  # False

# Sets are unordered — no index access
# fruits[0]  → TypeError: 'set' object is not subscriptable

Adding & Removing Elements

Sets are mutable — you can add and remove elements after creation. Python provides several methods for removing elements, each with different behaviour when the element is absent.

Python — set_add_remove.py
s = {1, 2, 3}

# add(x) — add one element
s.add(4)
print(s)          # {1, 2, 3, 4}
s.add(2)           # no-op — 2 already exists
print(s)          # {1, 2, 3, 4}

# update(iterable) — add multiple elements
s.update([5, 6])
print(s)          # {1, 2, 3, 4, 5, 6}
s.update({7, 8}, [9])   # multiple iterables

# remove(x) — remove element; raises KeyError if absent
s.remove(9)
# s.remove(99)  →  KeyError: 99

# discard(x) — remove element; NO error if absent
s.discard(8)
s.discard(99)      # safe — no KeyError

# pop() — remove and return an ARBITRARY element
val = s.pop()
print(val, s)     # some element removed (unpredictable!)

# clear() — remove ALL elements
temp = {1, 2, 3}
temp.clear()
print(temp)       # set()
Method Raises if absent? Effect
add(x)
No
Adds one element; ignored if already present
update(iter)
No
Adds all elements from iterable(s)
remove(x)
KeyError
Removes x; error if not found
discard(x)
No
Removes x; silent if not found
pop()
KeyError if empty
Removes and returns an arbitrary element
clear()
No
Removes all elements
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Set Operations — Union, Intersection, Difference, Symmetric Difference

Python sets support the four classical mathematical set operations. Each can be written using either a method or an operator symbol. The operator versions are more concise; the methods are more readable and accept any iterable.

Set Operations — Venn Diagrams (A = {1,2,3,4}, B = {3,4,5,6})
Union
A B
All elements from A and B
A | B or A.union(B)
{1,2,3,4,5,6}
Intersection
A B
Elements in both A and B
A & B or A.intersection(B)
{3, 4}
Difference (A - B)
A B
In A but not in B
A - B or A.difference(B)
{1, 2}
Symmetric Difference
A B
In A or B, but not both
A ^ B or A.symmetric_difference(B)
{1, 2, 5, 6}
Python — set_operations.py
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union — all elements from A and B
print(A | B)              # {1, 2, 3, 4, 5, 6}
print(A.union(B))         # same

# Intersection — elements in BOTH A and B
print(A & B)              # {3, 4}
print(A.intersection(B))  # same

# Difference — in A but NOT in B
print(A - B)              # {1, 2}
print(A.difference(B))    # same
print(B - A)              # {5, 6}  — B minus A

# Symmetric Difference — in A or B but NOT both
print(A ^ B)              # {1, 2, 5, 6}
print(A.symmetric_difference(B))  # same

# In-place update variants (modify A itself)
C = {1, 2}
C |= {3, 4}              # C = C | {3,4}
print(C)                  # {1, 2, 3, 4}

D = {1, 2, 3}
D &= {2, 3, 4}            # D = D & {2,3,4}
print(D)                  # {2, 3}

Subset, Superset & Disjoint Tests

Python sets support relational operations that test the containment relationship between two sets — whether one is entirely contained within another, or whether two sets share no elements at all.

Python — set_comparisons.py
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {10, 20}

# issubset(B) — True if A ⊆ B (all of A is in B)
print(A.issubset(B))       # True
print(A <= B)              # True  (operator form)
print(A < B)               # True  (proper subset — A ≠ B)

# issuperset(A) — True if B ⊇ A (B contains all of A)
print(B.issuperset(A))     # True
print(B >= A)              # True
print(B > A)               # True  (proper superset — B ≠ A)

# isdisjoint — True if NO elements in common
print(A.isdisjoint(C))     # True  — no overlap
print(A.isdisjoint(B))     # False — share 1,2,3

# Equality — same elements
print({1,2,3} == {3,2,1}) # True — order doesn't matter
Method Operator Meaning
A.issubset(B) A <= B Every element of A is in B
A.issuperset(B) A >= B Every element of B is in A
A.isdisjoint(B) — A and B share no elements
— A < B A is a proper subset (A ≠ B)
— A > B A is a proper superset (A ≠ B)

All Set Methods

Python sets have in-place update variants for each operation — these modify the set directly instead of returning a new one. These are the method equivalents of the |=, &=, -=, and ^= operators.

Python — set_methods.py
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# update(B) — add all elements of B into A (A |= B)
s = {1, 2}
s.update({3, 4})
print(s)     # {1, 2, 3, 4}

# intersection_update(B) — keep only elements in both (A &= B)
s = {1, 2, 3, 4}
s.intersection_update({3, 4, 5})
print(s)     # {3, 4}

# difference_update(B) — remove elements that are in B (A -= B)
s = {1, 2, 3, 4}
s.difference_update({3, 4, 5})
print(s)     # {1, 2}

# symmetric_difference_update(B) — keep elements in A or B not both (A ^= B)
s = {1, 2, 3}
s.symmetric_difference_update({2, 3, 4})
print(s)     # {1, 4}

# copy() — shallow copy
original = {1, 2, 3}
backup   = original.copy()
backup.add(99)
print(original)  # {1, 2, 3} ← unchanged

# Iteration and set comprehension
nums    = {1, 2, 3, 4, 5}
squares = {x**2 for x in nums}
print(squares)   # {1, 4, 9, 16, 25}

evens   = {x for x in nums if x % 2 == 0}
print(evens)     # {2, 4}

Frozen Sets

A frozenset is an immutable version of a set — created once, it can never be modified. Because it's immutable, it's hashable and can be used as a dictionary key or stored inside another set. All read-only set operations work on frozensets; modifying operations do not.

Python — frozenset.py
# Create frozenset
fs = frozenset({1, 2, 3})
print(fs)               # frozenset({1, 2, 3})
print(type(fs))          # <class 'frozenset'>

# ❌ Cannot modify a frozenset
# fs.add(4)    → AttributeError
# fs.remove(1) → AttributeError

# ✅ All read operations work
print(2 in fs)           # True
print(len(fs))            # 3

# ✅ Set operations return frozenset or set
fs2 = frozenset({3, 4, 5})
print(fs & fs2)          # frozenset({3})
print(fs | fs2)          # frozenset({1, 2, 3, 4, 5})

# ✅ Frozenset as dict key — HASHABLE!
permissions = {
    frozenset({"read"}):          "viewer",
    frozenset({"read", "write"}): "editor",
}
key = frozenset({"read"})
print(permissions[key])   # viewer

# ✅ Frozenset inside a set
set_of_sets = {frozenset({1,2}), frozenset({3,4})}
print(set_of_sets)

Real-World Use Cases

Sets shine in several everyday programming tasks where uniqueness and fast lookup matter. Here are the most common professional patterns:

Python — set_real_world.py
# ── 1. Remove duplicates from a list ────────────────
data   = [1, 2, 2, 3, 3, 4]
unique = list(set(data))
print(unique)              # [1, 2, 3, 4] (order may vary)

# Preserve order (Python 3.7+)
unique_ordered = list(dict.fromkeys(data))
print(unique_ordered)      # [1, 2, 3, 4]

# ── 2. Fast membership check ────────────────────────
VALID_ROLES = {"admin", "editor", "viewer"}
role = "admin"
if role in VALID_ROLES:    # O(1) — set, not list!
    print("Authorised")

# ── 3. Find common items (intersection) ─────────────
users_A  = {"alice", "bob", "carol"}
users_B  = {"bob", "dave", "carol"}
both     = users_A & users_B
print(both)                # {'bob', 'carol'}

# ── 4. Items in A but not B ──────────────────────────
only_A = users_A - users_B
print(only_A)              # {'alice'}

# ── 5. Tags / categories (union) ─────────────────────
post1_tags = {"python", "tutorial", "beginner"}
post2_tags = {"python", "advanced", "django"}
all_tags   = post1_tags | post2_tags
print(all_tags)

# ── 6. Validate input is subset of allowed values ────
ALLOWED  = {"read", "write", "delete"}
requested= {"read", "write"}
if requested.issubset(ALLOWED):
    print("All permissions valid")

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all set examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every set example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • A set is an unordered collection of unique, hashable elements. Sets automatically remove duplicates.
  • Create with {1, 2, 3} or set(iterable). Use set() — never {} — for an empty set.
  • Sets have O(1) membership testing — far faster than lists for checking if a value exists.
  • Modifying: add(), update(), remove() (raises on missing), discard() (safe), pop(), clear().
  • Set operations: union (|), intersection (&), difference (-), symmetric difference (^). In-place variants: |=, &=, -=, ^=.
  • Subset: A <= B; Superset: A >= B; Disjoint: A.isdisjoint(B).
  • A frozenset is an immutable, hashable set — can be used as dict key or stored inside another set.
  • Common uses: removing duplicates, fast membership checks, finding common/unique items between collections.
⚡
Free Resource
Download our Python Sets Cheat Sheet
Set creation, all operations, methods, frozenset & real-world patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Use set(). The syntax {} was already taken for creating an empty dictionary — Python uses curly braces with key-value pairs for dicts, and without any items {} defaults to dict.

empty_set  = set()    # ✅ <class 'set'>
empty_dict = {}      # ❌ <class 'dict'>
✓ Answer

Both remove an element from a set, but they differ in error behaviour when the element is absent:

  • remove(x) — raises KeyError if x is not in the set.
  • discard(x) — does nothing and raises no error if x is absent.

Use discard() when the element may or may not be present and you don't want to handle exceptions. Use remove() when absence of the element is unexpected and should signal an error.

✓ Answer

A | B (or A.union(B)) returns a new set containing all elements from both A and B — A and B are unchanged.

A |= B (or A.update(B)) modifies A in-place — adds all elements from B into A directly. No new set is created.

A = {1, 2}; B = {3, 4}
C = A | B        # new set {1,2,3,4}; A unchanged
A |= B            # A is now {1,2,3,4} in-place
✓ Answer

Sets are implemented as hash tables. When you test x in my_set, Python computes the hash of x and jumps directly to the bucket where it would be stored — typically a single operation, regardless of set size. This is O(1) constant time.

Lists store items sequentially. Testing x in my_list scans from the start until it finds x or reaches the end — O(n) time. For 1 million items, a list may need 1 million comparisons; a set needs approximately one.

✓ Answer

A frozenset is an immutable version of a set — once created, elements cannot be added or removed. Because it is immutable, it is hashable and can be used anywhere a hashable value is required.

Use frozenset when:

  • You need a set as a dictionary key (regular sets are unhashable)
  • You need a set inside another set
  • You want to guarantee a set cannot be accidentally modified (e.g. constants, configuration)
  • You need thread-safety — immutable objects are inherently safe for concurrent reads
MCQ 1 of 3
What does {1, 2, 3} & {2, 3, 4, 5} return?
MCQ 2 of 3
What does set("hello") produce?
MCQ 3 of 3
Which set method removes an element silently if it is not present?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel