Set
A set is an unordered collection of unique, hashable elements. Create one with curly braces: fruits = {"apple", "banana", "cherry"} or with the set() const...
What is a Set?
A set is an unordered collection of unique, hashable elements. Create one with curly braces: fruits = {"apple", "banana", "cherry"} or with the set() constructor: set([1, 2, 2, 3]) gives {1, 2, 3} — duplicates are removed automatically. Note: {} creates an empty dictionary, not an empty set; use set() for an empty set. Sets are mutable, but their elements must be immutable. You cannot have a set of lists, but you can have a set of tuples.
Set Operations
Sets support mathematical set operations. union: a | b or a.union(b) — all elements in either. intersection: a & b or a.intersection(b) — elements in both. difference: a - b or a.difference(b) — elements in a but not b. symmetric_difference: a ^ b — elements in one but not both. issubset: a <= b checks if all elements of a are in b. issuperset: a >= b. These operations make sets ideal for membership testing, deduplication, and comparing groups of items.
Modifying Sets
add(element) adds a single element. discard(element) removes an element without raising an error if absent. remove(element) removes an element, raising KeyError if absent. pop() removes and returns an arbitrary element (sets are unordered). update(iterable) adds all elements from an iterable. In-place versions of the mathematical operations: |= (union), &= (intersection), -= (difference), ^= (symmetric difference). clear() removes all elements.
Frozenset
A frozenset is an immutable version of a set. Create with frozenset(iterable). Because it is hashable, a frozenset can be used as a dictionary key or stored inside another set. This is useful when you need a collection of unique items that should itself be hashable. frozensets support all the same non-mutating operations as sets (union, intersection, etc.) but not add(), remove(), or other mutating methods.
Membership Testing Performance
The primary advantage of sets over lists for membership testing is speed. Checking x in my_list is O(n) — Python must examine each element. Checking x in my_set is O(1) — sets use hash tables. For large collections where you repeatedly check membership, converting a list to a set first can dramatically speed up your program. lookup_set = set(my_list); if item in lookup_set: is a very common optimisation pattern in competitive programming and data processing.
Exam Tip
Common set exam questions: what is the output of set([1,1,2,3,2])? {1, 2, 3}. Can you access elements of a set by index? No — sets are unordered and do not support indexing. What is the difference between discard() and remove()? Both remove an element, but discard() silently does nothing if the element is not present while remove() raises KeyError. What is the time complexity of x in s for a set? O(1) average case. What type of elements can a set contain? Only hashable (immutable) objects.