# Sets & Mathematical Operations

> Harness unordered collections of unique elements, O(1) membership testing, mathematical Venn diagram operations, and the empty set syntax trap.

Subject: Python | Lesson 8 of 24 | 6 min read
Interactive lesson: https://codewithanimation.in/python/sets
Previous: [Dictionaries & Hash Maps](https://codewithanimation.in/python/dictionaries.md) | Next: [Defining Functions & Return Values](https://codewithanimation.in/python/defining-functions.md)

## Unordered Collections of Unique Elements

A set is an unordered, mutable collection of distinct, hashable objects. Duplicate items added to a set are silently and automatically discarded: `{1, 2, 2, 3}` becomes `{1, 2, 3}`.

Under the hood, a set is implemented as a hash table where keys point to dummy values. Because lookup checks the hash value directly, checking membership with `x in my_set` runs in blazing-fast O(1) average constant time.

In contrast, checking `x in my_list` requires scanning elements one by one from left to right, taking O(n) linear time. For large collections, set lookups are thousands of times faster.

## Mathematical Set Operations & Venn Algebra

Python provides native operators that mirror mathematical set theory:

Union (`a | b`): Returns a new set containing all elements present in either set.

Intersection (`a & b`): Returns only the elements present in both sets simultaneously.

Difference (`a - b`): Returns elements that belong to set `a` but not to set `b`.

Symmetric Difference (`a ^ b`): Returns elements that exist in either `a` or `b`, but strictly not in both.

## Set Syntax & Operator vs Method Differences

Sets are constructed using curly braces: `colors = {"red", "green", "blue"}`, or by converting any iterable with `set([1, 2, 3])`.

Syntax trap: writing `{}` creates an empty dictionary, not an empty set. To create an empty set, you must use the constructor: `empty = set()`.

Operators vs Methods: operators like `a | b` require both operands to be set types. In contrast, set methods like `a.union([4, 5, 6])` accept any arbitrary iterable (lists, tuples, generators) without requiring explicit conversion.

## Common mistake: Unhashable Elements & Non-Subscriptable Access

Just like dictionary keys, all elements inside a set must be immutable and hashable. Trying to add a list or dictionary with `{1, [2, 3]}` raises `TypeError: unhashable type: 'list'`.

Sets are fundamentally unordered. You cannot access elements by position: running `my_set[0]` raises `TypeError: 'set' object is not subscriptable`.

Converting a list to a set to remove duplicates with `list(set(my_list))` does not preserve the original list's element order.

## Tip: Order-Preserving Deduplication

If you need to deduplicate a list while strictly maintaining the original element order, use `list(dict.fromkeys(my_list))` instead of `list(set(my_list))`. Because Python 3.7+ dictionaries preserve insertion order, `dict.fromkeys()` removes duplicates in O(n) time without scrambling order.

## Try it: The Venn Diagram & Set Algebra Stage

Select mathematical operations between Set A and Set B. Watch how the interactive Venn diagram highlights the matching regions and computes the resulting set in real time.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/sets

## Check yourself

### Question 1

What is the data type of the expression `empty_val = {}` in Python?

- A. dict (empty dictionary)
- B. set (empty set)
- C. tuple
- D. NoneType

Correct answer: A

In Python syntax, `{}` creates an empty dictionary `dict`. To create an empty set, you must explicitly call `set()`.

- Why not B: An empty set cannot be created with `{}` because `{}` is reserved for empty dictionaries. Use `set()`.
- Why not C: Empty tuples use parentheses `()`.
- Why not D: `{}` creates a valid empty dictionary object, not None.

### Question 2

Given `a = {1, 2, 3}` and `b = {2, 3, 4}`, what is the result of the symmetric difference `a ^ b`?

- A. {1, 4} (elements in either set, but not in both)
- B. {2, 3} (elements in both sets)
- C. {1, 2, 3, 4} (all elements)
- D. {1}

Correct answer: A

Symmetric difference `a ^ b` computes `(a | b) - (a & b)`: elements present in either set A or B, but excluding elements shared by both ({1, 4}).

- Why not B: {2, 3} is the intersection `a & b`, not the symmetric difference.
- Why not C: {1, 2, 3, 4} is the union `a | b`.
- Why not D: {1} is the difference `a - b`.

### Question 3

Why is `x in my_set` significantly faster than `x in my_list` for a collection with 1,000,000 elements?

- A. Sets use hash tables offering O(1) average lookup, whereas lists require O(n) sequential linear scanning.
- B. Sets store elements in binary search trees offering O(log n) lookup.
- C. Lists are encrypted in memory, making item lookups slow.
- D. Sets automatically run in parallel across all CPU cores.

Correct answer: A

Sets use open-addressing hash tables: checking membership takes O(1) constant time regardless of size. Lists must scan every element sequentially in O(n) time.

- Why not B: Python sets use open-addressing hash tables, achieving O(1) average time, not binary search trees.
- Why not C: Lists are unencrypted contiguous pointer arrays that require linear traversal.
- Why not D: Set operations run on the main thread via standard CPython hash table lookups.

## Remember this

- Sets store unordered, unique elements; duplicates are silently discarded.
- Membership testing (x in s) is O(1) average time, vastly outperforming O(n) list scans.
- Empty sets must be created with set(), because {} creates an empty dictionary.
- Set operations: union (|), intersection (&), difference (-), and symmetric difference (^).
- To remove duplicates while preserving list order, use list(dict.fromkeys(items)).
