Sets and Set Operations

A collection with no duplicates and no order, built for membership tests and for comparing two groups.

Overview

What a set gives up, and what it buys

Write a set with braces:

seen = {"red", "green", "red", "blue"}

Three items come out, not four: duplicates collapse silently. Print it twice and the order may differ, because there is no order to preserve.

In exchange, x in some_set is roughly constant time. On a list, the same question is a scan: Python looks at each element until it finds a match or runs out. On a few dozen items nobody notices. On two hundred thousand, the difference is milliseconds against microseconds, and the second program on this page measures it rather than asserting it.

sets.py

sets.py Python 3
Output

                    

set_algebra.py

set_algebra.py Python 3
Output

                    

Worth knowing

{} is an empty dict, not an empty set. Use set().
No duplicates and no order. If order matters, a set is the wrong container.
& intersection, | union, - difference, ^ in one but not both.
Membership is roughly constant time on a set and a full scan on a list. That gap is the whole reason to convert.

Sets and Set Operations: A Practical Guide

A set holds unique items in no particular order. That trade — giving up order and duplicates — buys near-instant membership tests and a small algebra for comparing two groups.

Deduplicating

The most common use is removing duplicates:

unique = set(votes)

If you need a list back, wrap it: list(set(votes)). If you need the original order kept, a set will not do it — use list(dict.fromkeys(votes)), since dictionaries do preserve insertion order.

The algebra

Four operators compare two sets, and they read like the English:

python & sql  # in both
python | sql  # in either
python - sql  # in the first only
python ^ sql  # in exactly one

Each replaces a loop with an if inside it. "Which users have both skills" is one character. Writing it as a loop is not wrong, it is just more code to read and more places to make a mistake.

The empty-set trap

{} is an empty dictionary. It has to be, because dictionaries claimed the braces first. An empty set is set(). This is worth remembering because {} looks exactly like what you want and behaves nothing like it.

What cannot go in

Set members must be hashable, for the same reason dictionary keys must be: the set decides where to store something from its hash, so that hash must never change. Numbers, strings and tuples are fine. Lists and dictionaries are not.

When not to use one

If order matters, if duplicates are meaningful, or if you need to index by position, use a list. A set answers one question extremely well — "is this in here?" — and refuses most others.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `{}` create?

  2. Why is `x in big_set` so much faster than `x in big_list`?

  3. `{"a", "b"} ^ {"b", "c"}` gives what?

Cheat sheet

Sets and Set Operations

A set holds unique items in no particular order. That trade — giving up order and duplicates — buys near-instant membership tests and a small algebra for comparing two groups.

PYTHON · vizlearn.in/python/sets_and_set_operations.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.