1.2.25Introduction to Programming (Python)

Sets — unique elements, set operations (union, intersection, difference)

1,886 words9 min readdifficulty · medium

What a set is

s = {3, 1, 2, 2, 3}      # duplicates collapse
print(s)                 # {1, 2, 3}  (order NOT guaranteed)
empty = set()            # {} is an empty DICT, not a set!

WHY uniqueness is automatic — the hashing idea


The four core operations

Let AA and BB be sets. Each operation answers a precise membership question.

Figure — Sets — unique elements, set operations (union, intersection, difference)

Worked Examples


More mistakes to steel-man


Key set algebra (derive, don't memorize)


Flashcards

What property makes a set's elements distinct?
All elements are unique; duplicate inserts are silently ignored.
How do you create an empty set (and why not {})?
set(); {} creates an empty dictionary.
Time complexity of x in s for a set vs a list?
Set ≈ O(1)O(1) (hash lookup); list ≈ O(n)O(n) (linear scan).
Why can't a list be an element of a set?
Set elements must be hashable/immutable; lists are mutable, so unhashable. Use a tuple.
Symbol & meaning of A | B?
Union — elements in A or B.
Symbol & meaning of A & B?
Intersection — elements in A and B.
What does A - B give, and is it symmetric?
Elements in A but not B; not symmetric (ABBAA-B \neq B-A).
What does A ^ B give?
Symmetric difference — elements in exactly one of A or B.
Difference between A.union(B) and A.update(B)?
union returns a new set; update mutates A in place.
One-liner to dedup a list L?
list(set(L)) (order not preserved).

Recall Feynman: explain to a 12-year-old

Imagine two boxes of stickers. A set is a box where you can't have two of the same sticker — if you drop a duplicate in, it just vanishes, leaving one. Now with two boxes:

  • Union = dump both boxes together into one big pile (no doubles).
  • Intersection = keep only stickers that are in both boxes.
  • Difference (Box A − Box B) = stickers in A that B doesn't have.
  • Symmetric difference = stickers that only one box has — the "not-shared" ones. And the box is fast: to check "do I already have this sticker?" it doesn't search the whole pile — it knows the exact spot to look.

Connections

  • Lists — ordered, indexed collections (sets trade order for fast membership)
  • Dictionaries — key-value & why {} is a dict
  • Hashing and Hashable Types
  • Tuples — immutable sequences (valid set elements)
  • Big-O Notation & Time Complexity
  • Boolean Logic — AND, OR, XOR (the algebra behind set ops)

Concept Map

implemented as

enables

gives

requires

mistake avoided by

supports

supports

supports

combined into

combined into

subtracted for

Set: unordered unique collection

Hash table

Automatic uniqueness

Hashable elements only

Membership O 1

Empty set needs set parens

Union A or B

Intersection A and B

Difference A not B

Symmetric difference exactly one

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Set ko samjho ek aisi peti ki tarah jisme har cheez sirf ek baar rakhi ja sakti hai. Agar tum duplicate daaloge to woh chup-chaap ignore ho jata hai — isliye unique elements free me mil jaate hain. Set unordered hota hai, yaani s[0] se kaam nahi chalega; sirf "yeh element andar hai ya nahi" pata chalta hai. Aur yeh check super-fast hai (x in sO(1)O(1)) kyunki andar hashing chal rahi hai — Python directly address jaanta hai, poori list scan nahi karta. Yahi sets ka asli superpower hai.

Char main operations yaad rakho English logic se: Union A | B matlab "A ya B me" (OR), sab cheezein ek pile me. Intersection A & B matlab "A aur B dono me" (AND), sirf common cheezein. Difference A - B matlab "A me hai par B me nahi" — aur dhyan rakho yeh symmetric nahi hai, A - B aur B - A alag hote hain. Symmetric difference A ^ B matlab "sirf ek me hai, dono me nahi".

Do bade traps: pehla, {} empty set nahi balki empty dictionary hai — empty set ke liye set() likho. Doosra, set ke andar list nahi daal sakte (unhashable error), tuple use karo. Real life me sabse common use 80/20 wala — kisi list ke duplicates hatane hote hain to bas list(set(L)). Bas yaad rakhna order chala jaata hai, agar order chahiye to dict.fromkeys(L).

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections