Need to check many items for membership, or compare two collections? A Python set stores unique, unordered members. Use a set when membership matters more than positional order, or when you need to find which items collections share. section 3.6.4 section 4.5.1
Create a set from existing data
Use braces for a small literal or set() to collect distinct items from an iterable: unique_evens = set((-2, 4, 0, 2, 4, 2)) assert unique_evens == {-2, 0, 2, 4} Only hashable objects can be set items. For example, {{"a": 0}} raises TypeError because the inner dictionary is unhashable. Do not rely on the order in which a set displays its items. section 5.1.3 section 3.5 section 3.6.3
The hash table underlying a set makes membership lookup approximately constant-time, O(1), as the collection grows. Checking a list instead requires traversing it, so lookup time grows with its length. Prefer a set when repeated membership checks are central to the task. section 3.5.1 section 4.5.1
Check whether recommended items cover a client's list
Convert a shared list once, then pass each client's list directly to issuperset(): good_stocks = ["AAPL", "GOOG", "AMZN", "NVDA"] recommended = set(good_stocks) assert recommended.issuperset(["GOOG", "AMZN"]) is True assert recommended.issuperset(["AMZN", "SNAP"]) is False To ask whether there is *any* overlap, use intersection() instead: assert bool(recommended.intersection(["AMZN", "SNAP"])) is True The intersection is nonempty, so bool() returns True. These named methods accept iterables; the corresponding operators require set operands. section 3.6.1 section 3.6.2 section 3.6.3
When both operands are sets, four operations select members by relationship:
- Union, A | B: members in either set. section 3.6.3
- Intersection, A & B: members in both sets. section 3.6.3
- Symmetric difference, A ^ B: members in one set but not both. section 3.6.3
- Difference, A - B: members in A but not B. section 3.6.3
Select tasks by relationship
a = {"Homework", "Laundry", "Grocery"} b = {"Laundry", "Gaming"} assert a & b == {"Laundry"} assert a - b == {"Homework", "Grocery"} assert a ^ b == {"Homework", "Grocery", "Gaming"} For readability—particularly when an input is a list—consider the named methods intersection(), difference(), and symmetric_difference() rather than converting every input merely to use an operator. section 3.6.3














