A set is an unordered collection of unique, hashable values. Duplicates are discarded automatically.
colours = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3, 3, 3])
empty = set(){} creates an empty dictionary, not an empty set. Use set() for an empty set.
Removing duplicates#
values = [1, 2, 2, 3, 1, 4]
unique = set(values)
print(unique)
print(len(unique))Sets do not preserve order. If order matters, remove duplicates with dict.fromkeys(values) instead.
Membership#
Set membership is average-case constant time, which makes sets a good choice for repeated lookups:
valid_roles = {"admin", "editor", "viewer"}
print("editor" in valid_roles) # True
print("owner" in valid_roles) # FalseFor one check, a tuple or list is fine. For many checks against the same collection, a set avoids scanning every item each time.
Modifying a set#
tags = {"python", "tutorial"}
tags.add("beginner")
tags.discard("tutorial")
print(tags)add() inserts one value. discard() removes a value if present and does nothing otherwise. remove() raises KeyError when the value is missing. clear() empties the set.
Set operations#
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a - b) # difference: {1, 2}
print(b - a) # {5, 6}
print(a ^ b) # symmetric difference: {1, 2, 5, 6}The printed order can vary because sets are unordered. In this environment small integer sets often print in ascending order, but do not depend on it.
Named methods are equivalent and can update in place:
a = {1, 2, 3}
b = {3, 4}
a.update(b) # union in place
a.intersection_update({2, 3, 4})
a.difference_update({3})
print(a)Subsets and supersets#
required = {"name", "email"}
provided = {"name", "email", "phone"}
print(required <= provided) # True: subset
print(provided >= required) # True: superset
print(required.isdisjoint({"phone", "address"})) # TrueThese checks are useful for permission systems and validation.
Sets of tuples#
A set can contain any hashable value, including tuples:
visited = {(0, 0), (1, 2), (0, 0)}
print(visited) # {(0, 0), (1, 2)}This is a compact way to track unique coordinates or pairs.
When to use a set#
- Removing duplicates when order is irrelevant.
- Fast membership checks.
- Comparing collections, such as finding shared or missing items.
- Tracking seen values during a scan.
Use a list when order and duplicates matter. Use a dictionary when each value needs associated data.
Practice#
Given two lists of names, print the names that appear in both lists, the names that appear in only one, and the total number of unique names. Use set operations rather than nested loops.
