Use set operations when a program must compare collections by membership rather than preserve their order. They help answer questions such as whether every client stock appears in a recommended list, and they can combine or filter related sets. section 3.6 section 3.6.3
Choose the operation that matches the membership relationship:
- Union (| or union) selects members from either set. section 3.6.3
- Intersection (& or intersection) selects members common to both sets. section 3.6.3
- Symmetric difference (^ or symmetric_difference) selects members belonging to one set but not both. section 3.6.3
- Difference (- or difference) selects members in one set that are absent from the other. section 3.6.3
- Use issubset or issuperset to test containment; methods accept iterables, while operators require set objects. section 3.6.3
Check whether every client stock is recommended
good_stocks = ["AAPL", "GOOG", "AMZN", "NVDA"] client0 = ["GOOG", "AMZN"] client1 = ["AMZN", "SNAP"] good_stocks_set = set(good_stocks) print(good_stocks_set.issuperset(client0)) # True print(good_stocks_set.issuperset(client1)) # False Convert the shared recommended list once, then call issuperset for each client list. This is more concise than repeatedly writing a membership loop, and avoids converting every client list when the recommended collection is the presumed superset. section 3.6.1
Figure 3.8 Set operations in Python. Four common set operations are shown with their respective mathematical notations, Venn diagrams, and operations in Python. Union consists of members from A and B. Intersection consists of members common to A and B. Symmetric difference consists of members of one set but not both. Difference consists of members of one set but not both.
Use the visual comparison to distinguish union, intersection, symmetric difference, and difference by their membership regions. section 3.6.3

