TExcelTAD
Home › Python › Python Sets

Python Sets

A set is an unordered collection of unique items. Sets are perfect for removing duplicates, for fast "is this in here?" checks, and for comparing groups — which items do two groups share, which are only in one?

python · try it yourself
tags = {"python", "web", "python", "data"}
print(len(tags))           # the duplicate was dropped
print("web" in tags)
print(sorted(tags))
3
True
['data', 'python', 'web']

Note: Sets have no order. Printing a set of strings may show the items in a different order each time you run the program. In this course we often print sorted(my_set) to keep the output predictable.

Key properties

Property Meaning
Unordered No indexes, no slicing
Unique Duplicates are removed automatically
Mutable You can add and remove items
Hashable items only Items must be immutable: numbers, strings, tuples — not lists

Creating sets

python · try it yourself
primes = {2, 3, 5, 7}
letters = set("banana")       # from any iterable
empty = set()                 # NOT {} - that is an empty dict
print(primes)
print(sorted(letters))
print(type(empty).__name__, type({}).__name__)
{2, 3, 5, 7}
['a', 'b', 'n']
set dict

Removing duplicates

The fastest way to deduplicate a list is to pass it through a set. If you need to keep the original order, use dict.fromkeys() instead:

python · try it yourself
visits = ["home", "about", "home", "blog", "about", "home"]
print(len(set(visits)), "unique pages")
print(list(dict.fromkeys(visits)))    # unique, original order kept
3 unique pages
['home', 'about', 'blog']

Adding and removing

Method Effect
add(x) Add one item
update(iterable) Add many items
remove(x) Remove x, KeyError if missing
discard(x) Remove x if present, no error otherwise
pop() Remove and return an arbitrary item
clear() Remove everything
python · try it yourself
seen = {1, 2}
seen.add(3)
seen.add(2)            # already present: nothing happens
seen.update([4, 5])
seen.discard(10)       # safe even though 10 is absent
seen.remove(1)
print(seen)
{2, 3, 4, 5}

Set operations

This is where sets shine. They support the operations you may remember from maths class, both as operators and as methods:

Operation Operator Method Result contains
Union a | b a.union(b) items in either set
Intersection a & b a.intersection(b) items in both
Difference a - b a.difference(b) items in a but not b
Symmetric difference a ^ b a.symmetric_difference(b) items in exactly one
python · try it yourself
python_devs = {"An", "Binh", "Chau", "Duc"}
rust_devs = {"Chau", "Duc", "Giang"}

print(sorted(python_devs | rust_devs))
print(sorted(python_devs & rust_devs))
print(sorted(python_devs - rust_devs))
print(sorted(python_devs ^ rust_devs))
['An', 'Binh', 'Chau', 'Duc', 'Giang']
['Chau', 'Duc']
['An', 'Binh']
['An', 'Binh', 'Giang']

Subsets and supersets

python · try it yourself
required = {"read", "write"}
granted = {"read", "write", "delete"}
print(required <= granted)            # subset
print(granted.issuperset(required))
print(required.isdisjoint({"admin"})) # no items in common
True
True
True

Frozen sets

A frozenset is an immutable set. Because it can't change, it is hashable and can be used as a dictionary key or stored inside another set:

python · try it yourself
pair = frozenset({"x", "y"})
groups = {pair, frozenset({"z"})}
print(len(groups))
print(frozenset({"y", "x"}) in groups)
2
True

Tip: Checking x in some_set is very fast even for millions of items, while x in some_list has to scan the whole list. If you test membership in a loop, convert the list to a set first.

Test yourself

How do you create an empty set?

  1. {}
  2. set()
  3. []
  4. empty_set()

What is {1, 2, 3} & {2, 3, 4}?

  1. {1, 2, 3, 4}
  2. {2, 3}
  3. {1, 4}
  4. {1}

Which method removes an item without raising an error if it's missing?

  1. remove()
  2. pop()
  3. discard()
  4. delete()