Python: Sets

Work with unordered collections of unique elements. Sets excel at deduplication, fast membership testing, and expressing mathematical relationships between groups of data.

Creating Sets

A set is an unordered, mutable collection that only holds unique values. Duplicate elements are silently dropped. Sets are defined using curly bracesor the set() constructor. One important gotcha: an empty pair of curly braces creates a dictionary, not a set.

Set Rules

Sets enforce uniqueness and only accept hashable (immutable) elements.

  • Use set() to create an empty set, never {}
  • Duplicate values are automatically removed on creation
  • Elements must be hashable: numbers, strings, and tuples are fine
  • Lists and dicts cannot be set elements because they are mutable (unhashable)

Set Initialization

Python

Creating sets from literals and iterables.

Adding and Removing Elements

Use add() to insert a single element. To remove, you have two options:remove()raises a KeyErrorif the element is not found, whilediscard()does nothing. Choose discard()when you are not certain the element is present.

Mutating a Set

Python

Safe and unsafe removal patterns.

Set Operations

Sets support the classic mathematical operations from set theory. You can use either the symbolic operators or the named methods. The methods are slightly more flexible since they accept any iterable, whereas the operators require both sides to be sets.

Union, Intersection, Difference, and Symmetric Difference

Python

All four core set operations shown side by side.

issubset, issuperset, and isdisjoint

These three methods let you test the relationship between two sets. They all return a boolean, making them ideal for conditional checks.

Relationship Tests

Python

Checking how two sets relate to each other.

Set Comprehensions

Set comprehensions follow the same pattern as list comprehensions but produce a set, which means duplicates are automatically eliminated. They are a clean way to transform or filter a sequence into a unique collection.

Building Sets Expressively

Python

Concise set creation from existing data.

Frozenset

A frozenset is the immutable version of a set. Because it cannot change, it is hashable and can therefore be used as a dictionary key or as an element inside another set. All the read operations (membership tests, set comparisons) still work; mutation operations like add()and remove() do not.

Immutable Sets

Python

Using frozensets as dictionary keys.

Set vs List vs Tuple

Picking the right collection type makes your intent clear to other readers and keeps your code efficient. Here is a concise summary of when each one fits best.

Choosing the Right Container

Each type has a distinct purpose and set of trade-offs.

  • List: ordered, mutable, allows duplicates. Use for sequences that grow/shrink.
  • Tuple: ordered, immutable, allows duplicates. Use for fixed records and function return values.
  • Set: unordered, mutable, no duplicates. Use for deduplication and membership checks.
  • Frozenset: unordered, immutable, no duplicates. Use when a set must be hashable.

Membership Testing with in

The in operator works on all Python collections, but its performance varies significantly. For lists and tuples, Python scans every element until it finds a match - O(n) time. For sets, it computes a hash and checks a single bucket - O(1) average time. This makes sets the right tool when you need to check membership repeatedly on a large collection.

Membership Performance

Python

Why sets beat lists for contains checks.

Quiz - Test Your Knowledge

Put your knowledge of Python sets to the test. Pay close attention to the difference between operators and methods, and remember the key constraint around what can and cannot be stored in a set.

Knowledge Check

1. Which of these correctly creates an empty set?

2. What is the difference between remove() and discard() when the element is not found?

3. Which operator gives you elements that are in either set, but not in both?

4. What does {1, 2, 3} & {2, 3, 4} evaluate to?

5. Which method checks if two sets share no elements at all?

6. What is a frozenset?

7. Why is membership testing faster in a set than in a list?

8. Which of these will cause a TypeError when added to a set?