๐Ÿ”ตSets: Operations, Membership, FrozensetLESSON

Sets: Operations, Membership, Frozenset

A set is an unordered collection of unique, hashable items. Sets excel at two things: eliminating duplicates and fast membership testing. Under the hood Python implements sets as hash tables, giving O(1) average-time for add, remove, and membership checks regardless of how large the set grows.

Creating Sets

Adding and Removing Elements

The key difference: remove() raises KeyError on a missing element; discard() silently does nothing. Prefer discard() when you're not sure whether the element exists.

Set Operations

Sets support all classical mathematical set operations with both method syntax and operators:

Update Variants (in-place)

Subset and Superset Tests

Frozenset โ€” Immutable Sets

A frozenset is an immutable version of a set. Once created it cannot be modified โ€” no add(), remove(), or update operations. Because it is immutable and hashable, a frozenset can be used as a dictionary key or stored inside another set.

Membership Testing: O(1) vs O(n)

This is sets' killer feature. Python looks up items in a set via hash, so membership testing does not slow down as the collection grows.

When to Use Sets

SituationUse
Remove duplicates from a listlist(set(lst))
Fast membership test (thousands+ items)set
Find common/unique items between sequencesSet operations
Need an immutable, hashable setfrozenset
Need ordered unique itemsKeep a list + a set for dedup

Knowledge Check

What is the difference between set.remove(x) and set.discard(x)?

Why can a frozenset be used as a dictionary key, but a regular set cannot?

Which set operation returns elements that are in either set but NOT in both?