Introduction & Syntax
Sets · Study material
A set is an unordered collection of unique, hashable items. Sets answer questions that lists answer slowly: Is this user already registered? Which students take both courses? Which tags are new? Membership tests on a set are fast however big it gets, and the maths operations – union, intersection, difference – are one operator each. Tests probe the traps: {} is a dict, sets cannot be indexed, 1 and True are the same element, and remove() differs from discard(). This topic covers it all, then 50 practice questions run on Python 3.
On this page
- Creating sets – and why {} is not one
- Adding and removing: add, update, remove, discard, pop
- Union, intersection, difference, symmetric difference
- Subset, superset and disjoint tests
- Hashable elements, frozenset and set comprehensions
- Removing duplicates, with and without keeping order
Creating sets
Write items in braces, or convert an iterable with set() – duplicates are dropped automatically. {} creates an empty dictionary; an empty set is set(). Sets have no order and no indexes: s[0] is a TypeError, and the order you see when printing is not something to rely on (for strings it can even change from one run to the next). Sort a set when you need a fixed order.
primes = {2, 3, 5, 7}
digits = set([1, 2, 2, 3, 3, 3]) # duplicates disappear
letters = set("banana") # set of the characters
empty = set() # {} would be an empty DICT
print(primes, digits, len(digits))
print(sorted(letters), type({}).__name__, type(empty).__name__)
print(5 in primes, 4 not in primes)
{2, 3, 5, 7} {1, 2, 3} 3
['a', 'b', 'n'] dict set
True TrueAdding and removing elements
add(x) inserts one element; update(iterable, …) inserts many. remove(x) raises KeyError if x is missing, discard(x) does not. pop() removes and returns an arbitrary element (KeyError on an empty set), and clear() empties the set.
ids = {101, 102}
ids.add(103) # one element
ids.add(101) # already present: nothing happens
ids.update([104, 105], (106,)) # many elements from iterables
print(ids)
ids.remove(106) # KeyError if absent
ids.discard(999) # silently ignores a missing element
print(ids, len(ids))
ids.clear()
print(ids)
{101, 102, 103, 104, 105, 106}
{101, 102, 103, 104, 105} 5
set()Set operations
| Operation | Operator | Method | Result |
|---|---|---|---|
| Union | a | b | a.union(b) | in a or b |
| Intersection | a & b | a.intersection(b) | in both |
| Difference | a - b | a.difference(b) | in a but not b |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | in exactly one |
Operators need sets on both sides; methods accept any iterable. Each has an in-place form (|=, &=, -=, ^= or update(), intersection_update() …). The plain methods return a new set and leave the original unchanged.
python = {1, 2, 3, 4} # roll numbers enrolled in Python
java = {3, 4, 5} # … and in Java
print(python | java) # union: in either
print(python & java) # intersection: in both
print(python - java) # difference: Python only
print(java - python) # (order matters for difference)
print(python ^ java) # symmetric difference: in exactly one
print(python.union([9]), python.intersection(range(3, 10))) # methods accept any iterable
{1, 2, 3, 4, 5}
{3, 4}
{1, 2}
{5}
{1, 2, 5}
{1, 2, 3, 4, 9} {3, 4}Subset, superset and disjoint
a <= b (issubset) – every element of a is in b; a < b – subset and not equal. >= and > are the superset tests, and isdisjoint() checks that two sets share nothing. Two sets are equal when they have the same elements, regardless of order.
required = {"python", "sql"}
skills = {"python", "sql", "git"}
print(required <= skills, required.issubset(skills)) # subset
print(skills >= required, skills.issuperset(required)) # superset
print(required < skills, skills < skills) # proper subset: not equal
print(required.isdisjoint({"java", "c"})) # no common element
print(sorted(skills - required))
True True True True True False True ['git']
Only hashable elements
Set elements must be hashable: numbers, strings, tuples of hashable items and frozensets are; lists, dicts and sets are not. Because 1 == True == 1.0 and they hash equally, a set keeps only one of them – the first one added.
s = {1, "a", (2, 3), 4.5} # numbers, strings, tuples: all hashable
print(len(s))
try:
{[1, 2]} # a list is mutable, so it cannot be in a set
except TypeError as e:
print("TypeError:", e)
print({1, True, 1.0, 2}) # 1 == True == 1.0 with the same hash: ONE element
print(len({0, False, 0.0, ""}))
4
TypeError: unhashable type: 'list'
{1, 2}
2frozenset and set comprehensions
A frozenset is an immutable set, so it can be a dictionary key or an element of another set – useful for unordered pairs. A set comprehension {expr for x in it if cond} builds a set in one line.
pair = frozenset({"Delhi", "Agra"}) # immutable set: hashable
routes = {pair: 233}
print(routes[frozenset({"Agra", "Delhi"})]) # order does not matter
squares = {n * n for n in range(-3, 4)} # set comprehension
print(sorted(squares))
words = ["Hi", "hi", "HELLO", "hello", "hey"]
print(sorted({w.lower() for w in words}))
233 [0, 1, 4, 9] ['hello', 'hey', 'hi']
Common mistakes
- s = {} then
s.add(x)– {} is a dict: AttributeError. - Indexing a set – s[0] is a TypeError; convert or sort first.
- Expecting insertion order – use dict.fromkeys() to dedupe in order.
- remove() on a missing element – KeyError; use discard().
- a + b – sets use | for union.
- Calling a.union(b) and ignoring the result – a is unchanged; use a |= b.
- Putting lists in a set – convert them to tuples.
Key points to remember
- Sets hold unique, hashable items with no order and no index.
- set() is empty; {} is an empty dict.
- Membership tests are O(1) on average.
- | & - ^ give union, intersection, difference, symmetric difference.
- remove raises KeyError; discard does not.
- 1, True and 1.0 count as the same element.
- frozenset is the immutable, hashable set.
Frequently asked questions
Why is checking "x in set" faster than "x in list"?
A set finds x through its hash in roughly constant time; a list must compare items one by one (O(n)).
Does a set keep insertion order?
No – unlike dict, set order is an implementation detail. For an ordered unique collection use dict.fromkeys(items).
Can a set contain another set?
Only a frozenset, because a normal set is mutable and therefore unhashable.
Where can I learn more?
Read Python Sets and Choosing the Right Collection in the Python tutorial, then practise with the exercises below.