Python · Module 04: Built-In Data StructuresTutorial 12 of 30
All Tutorials·~1.5 hrs

4.4 Sets & Python Comprehensions (List, Dict & Set)

Eliminate duplicates in 1 line with Python sets, master Venn diagram set math, and write clean, idiomatic List, Dict, and Set Comprehensions.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What Is a set? (The VIP Guest-List Analogy)

A Python set is like a VIP guest list at a concert entrance:

  • No duplicates allowed: If you add "Riya" twice, she still appears only once.
  • Unordered: Sets have no positional index (s[0] raises TypeError), because items are stored by hash bucket rather than sequence position.
  • Blazing-fast O(1) membership testing: Checking "Riya" in vip_set computes a single hash lookup instead of scanning every element one by one.

Why set Destroys list for Membership Checks

If you have a list of 1,000,000 banned user IDs and check if user_id in banned_list: inside a loop, Python performs a linear O(N) scan every single time — turning a simple script into an O(N²) bottleneck that freezes for minutes. Converting it once with banned_set = set(banned_list) drops every lookup to O(1) average time, finishing in milliseconds.

PYTHON
# Remove duplicates from a list in 1 line!
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com"]
unique_emails = set(emails)
print(unique_emails)     # {'a@x.com', 'b@x.com', 'c@x.com'}

# Need deduplication WHILE preserving original order? Use dict.fromkeys()!
ordered_unique = list(dict.fromkeys(emails))  # ['a@x.com', 'b@x.com', 'c@x.com']

# Beginner Trap: {} creates an empty DICT, NOT an empty set!
empty_dict = {}          # dict!
empty_set  = set()       # ✓ Empty set!

Safe Mutation & Hashability Rules

  • .add(x) inserts one element; .update(iterable) inserts many.
  • .discard(x) vs .remove(x): Both delete x, but .remove(x) crashes with KeyError if x is missing, while .discard(x) silently does nothing — making .discard() much safer in production code.
  • Hashable elements only: Just like dictionary keys, set elements must be immutable/hashable (int, str, tuple, frozenset). You cannot put a mutable list or dict inside a set. If you need a set inside another set or as a dictionary key, use Python's immutable frozenset.

2. Mathematical Set Operations (Venn Diagrams in 1 Character!)

Sets shine whenever you compare two collections — finding mutual friends, auditing missing permissions, detecting newly added users, or comparing CSV exports:

Visual: Python Set Operations on `A = {1, 2, 3}` and `B = {3, 4, 5}`
A | B (Union)1,234,5{1, 2, 3, 4, 5}All unique itemsA & B (Intersect)1,234,5{3}Only in BOTHA - B (Diff)1,234,5{1, 2}In A, NOT in BA ^ B (Sym Diff)1,234,5{1, 2, 4, 5}In ONE, not both
PYTHON
a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)   # {1, 2, 3, 4, 5}  — Union (in A or B)
print(a & b)   # {3}              — Intersection (in BOTH A and B)
print(a - b)   # {1, 2}           — Difference (in A, NOT in B)
print(a ^ b)   # {1, 2, 4, 5}     — Symmetric Difference (in either, NOT both)
OperatorMethod EquivalentReal-World Engineering Use Case
A | BA.union(B)Merge tags from two microservices without duplicates
A & BA.intersection(B)Mutual followers, shared skills between resume & job description
A - BA.difference(B)Find required permissions missing from a user's role (required - granted)
A ^ BA.symmetric_difference(B)Detect config keys that changed between staging and production
A <= BA.issubset(B)Verify every requested permission is allowed (requested <= allowed)

3. List, Dict & Set Comprehensions (Python's Signature Feature)

Suppose you want the squares of all even numbers from 1 to 5. Instead of initializing an empty list and writing a 4-line for loop with .append(), Python lets you express the entire transformation in one crystal-clear expression:

Visual: Anatomy of a Python List Comprehension (1 Line Replaces a 4-Line Loop!)
[n * nfor n in range(1, 6)if n % 2 == 0]1. Transform ExpressionWhat goes into new list2. Loop SourceItems: 1, 2, 3, 4, 53. Optional Filter → [4, 16]Keeps only even numbers (2, 4)
PYTHON
# 1) List Comprehension -> [4, 16]
even_squares = [n * n for n in range(1, 6) if n % 2 == 0]

# 2) Dict Comprehension -> {'hi': 2, 'python': 6, 'code': 4}
words = ["hi", "python", "code"]
lengths = {w: len(w) for w in words}

# 3) Set Comprehension -> unique first letters {'h', 'p', 'c'}
initials = {w[0] for w in words}

The #1 Comprehension Syntax Rule: Filter if vs. Conditional if / else

Beginners frequently mix up where if goes inside a comprehension. Remember this clean split:

  • Filtering (keeping only some items) goes at the END: [n for n in nums if n > 0]
  • Transforming (choosing between two values for every item) goes at the FRONT: ["even" if n % 2 == 0 else "odd" for n in nums]

Bonus: Generator Expressions (O(1) Memory!)

Swap square brackets [...] for parentheses (...) when feeding a huge sequence into sum(), any(), all(), or max(). Instead of allocating a massive intermediate list in RAM, a generator expression computes one item at a time:

PYTHON
# ❌ Allocates a 10-million-element list in memory first
total_heavy = sum([n * n for n in range(10_000_000)])

# ✅ Streams one number at a time in O(1) memory!
total_light = sum(n * n for n in range(10_000_000))

Readability Rule: If a comprehension needs more than one for loop or complex nested if/else logic, write a normal for loop instead. Clean, obvious code always beats clever one-liners!


4. Interactive Trace: Deduplicating & Transforming Data

Tracing Set Deduplication & List Comprehension
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→tags = ["py", "sql", "py", "dsa"]
2unique = set(tags)
3upper_tags = [t.upper() for t in sorted(unique)]
4print(upper_tags)
Variables in Memory
tags["py", "sql", "py", "dsa"]list
Console Output
(nothing printed yet)
What just happened: We start with a list containing a duplicate tag "py".

Quick Quiz: Module 4.4 — Sets & Comprehensions

Q1.How do you create an EMPTY set in Python?
Q2.Given `A = {1, 2, 3}` and `B = {2, 3, 4}`, what does `A & B` return?
Q3.What does `[x * 2 for x in [1, 2, 3, 4] if x > 2]` evaluate to?

Keep Exploring: Related Lessons & Tools

All Courses →